在将Ben的答案包含在代码中之后,它似乎起作用了
原题:
我试图使用dup2:
最后的输出是(空白),文件"in“是(空白)&文件"out”的输出为"ls -al“。
知道会发生什么吗?
int main()
{
pid_t pid;
int i;
int inFileDes,outFileDes;
inFileDes=open("in",O_RDWR | O_CREAT,S_IRUSR | S_IWUSR);
outFileDes=open("out",O_RDWR | O_CREAT,S_IRUSR | S_IWUSR);
for(i=0;i<3;i++)
{
if((pid=fork())==0)
{
switch(i)
{
case 0:
dup2(outFileDes,1);
execl("/bin/ls","ls","-al",0);
break;
case 1:
// originally:
dup2(outFileDes,0); // dup2(outFileDes,1);
dup2(inFileDes,1); // dup2(inFileDes,0);
execl("/bin/grep","grep","foo",0); //lines having foo
break;
case 2:
dup2(inFileDes,0);
execl("/bin/grep","grep","bar",0); //lines having foo & bar
break;
}
exit(-1); //in error
}
waitpid(pid,NULL,0);
}
close(inFileDes);
close(outFileDes);
return(0);
}发布于 2010-09-04 13:29:16
您的open调用将创建一个空文件"in“,而没有任何程序会写入该文件,因此这是预期的。因为grep的两个实例都是从空文件中读取的,所以它们的输出也是空的。
您真正想要的是使用pipe函数获取一对句柄,它被写成一个程序并在下一个程序中读取。您需要调用它两次,因为您在子进程之间有两组连接。
https://stackoverflow.com/questions/3642453
复制相似问题