我不太确定如何在两个子进程之间创建管道。这是我做的方式:在C UNIX shell中管道
pipe(&fd[0]); //Create a pipe
proc1 = fork();
//Child process 1
if (proc1 == 0)
{
close(fd[0]); //process1 doenst need to read from pipe
close(STD_INPUT); //prepare for output
dup(fd[1]); //Standard output = fd[1]
close(fd[1]);
execvp(parameter[0], parameter); //Execute the process
}
else
{
proc2 = fork();
if (proc2 == 0)
{
close(fd[1]);
close(STD_OUTPUT);
dup(fd[0]);
close(fd[0]);
execvp(parameter2[0], parameter2);
}
//Parent process
else
{
waitpid(-1, &status, 0); //Wait for the child to be done
}
}
我试图重定向一个子进程到另一个的输出,但我想我犯了一个错误,在第二子进程的管道,因为当我运行程序与第二个子进程我得到不正确的结果(像一个简单的执行,如“ls”执行不当),但是,如果我删除第二个子进程,程序运行良好(不包括管道,只是简单的fork:ls,ls -l,ps等)。