【发布时间】:2016-02-29 16:09:16
【问题描述】:
我在用 C 语言编程 Linux 方面有点新手(我搜索了类似的线程但没有任何帮助),所以我陷入了以下问题:
我想在 C 中为 Linux 创建一个 shell(使用 fork()、exec()、pipe(),它从终端 stdin 获取带有参数和管道的命令作为输入(例如“sort foo | uniq - c | wc -l"),它执行它然后请求下一个命令等。
我分离了不同的命令、它们的参数等,我为每个子进程创建了 1 个子进程,但我不能将每个子进程的输出链接到下一个子进程的输入(以及终端中 stdout 的最后一个输出) )。
任何人都可以帮助做正确的管道以使其启动和运行吗??
如需更多信息,请询问... 提前致谢
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define P_READ 0
#define P_WRITE 1
pid_t pID, chID;
char input[100];
char * params[100][100];
char * funcs[100];
char * par;
char * fun;
int i, j, k, stat, infd[2], outfd[2];
//Pipe read
void read_en(int * infd)
{
dup2(infd[P_READ], STDIN_FILENO);
close(infd[P_READ]);
close(infd[P_WRITE]);
}
//Pipe write
void write_en(int * outfd)
{
dup2(outfd[P_WRITE], STDOUT_FILENO);
close(outfd[P_READ]);
close(outfd[P_WRITE]);
}
//Fork, read from pipe, write to pipe, exec
void fork_chain(int * infd, int * outfd, int i)
{
pID = fork();
if (pID == 0)
{
if (infd != NULL)
{
read_en(infd);
}
if (outfd != NULL)
{
write_en(outfd);
}
execvp(params[i][0], params[i]);
fprintf(stderr, "Command not found!\n");
exit(1);
}
else if (pID < 0)
{
fprintf(stderr, "Fork error!\n");
exit(1);
}
else
{
chID = waitpid(-1, &stat, 0);
}
}
int main()
{
printf("\n$");
fgets(input, sizeof(input), stdin);
strtok(input, "\n");
while (strcmp(input, "exit") != 0)
{
//Separate each command
k = 0;
fun = strtok(input, "|");
while (fun != NULL)
{
funcs[k] = fun;
fun = strtok(NULL, "|");
k++;
}
//Separate each command's parameters
for (i = 0; i < k; i++)
{
j = 0;
par = strtok(funcs[i], " ");
while (par != NULL)
{
params[i][j] = par;
par = strtok(NULL, " ");
j++;
}
params[i][j] = NULL;
}
//Fork, pipe and exec for each command
for (i = 0; i < k; i++)
{
if (i == 0)
{
pipe(outfd);
fork_chain(NULL, outfd, 0);
infd[P_READ] = outfd[P_READ];
infd[P_WRITE] = outfd[P_WRITE];
}
else if (i == k-1)
{
fork_chain(infd, NULL, 1);
close(infd[P_READ]);
close(infd[P_WRITE]);
}
else
{
pipe(outfd);
fork_chain(infd, outfd, i);
close(infd[P_READ]);
close(infd[P_WRITE]);
infd[P_READ] = outfd[P_READ];
infd[P_WRITE] = outfd[P_WRITE];
}
}
//Ask for next input
printf("\n$");
fgets(input, sizeof(input), stdin);
strtok(input, "\n");
}
return (0);
}
【问题讨论】:
-
如果不重复,相关:stackoverflow.com/q/5060350/694576
-
你提到的线程,只有大约 2 个孩子。我想要超过 2 个,这就是问题所在......