所以我有一个任务,我必须处理管道中的n个命令.这些命令基于Linux.如果我的理解是正确的,我知道我必须创建一个for循环,不断地fork()主进程的子进程,并执行这些子进程,然后通过管道连接.这是我目前为止的代码.
void main(void)
{
char **cmds[3];
char *c1[] = { "ls", "-l", "/etc", 0 };
char *c2[] = { "head", "-n", "10", 0 };
char *c3[] = { "tail", "-n", "5", 0 };
cmds[0] = (char **)c1;
cmds[1] = (char **)c2;
cmds[2] = (char **)c3;
int pid, status;
pid = fork();
if(pid == 0){//child proccess
int fd[2];
int infd;
int i;
for(i = 0; i < 2; i++){
pipe(fd);
int ppid;
ppid = fork();
if(ppid > 0){
dup2(fd[1], 1);
close(fd[0]);
//executes the nth command
execvp(*(cmds+i)[0], *(cmds+i));
}else if(ppid == 0){
dup2(fd[0], 0);
close(fd[1]);
//executes the n+1th command
execvp(*(cmds+i+1)[0], *(cmds+i+1));
}
}
}else if (pid > 0){//parents proccess
while((pid = wait(&status)) != -1);
}
}
就目前的程序而言,我只能传输第一个和第二个命令,但由于某些原因,第三个命令完全没有被检测到.我该怎么解决这件事?