dup2 的问题
将 Ben Voigt 的答案合并到代码中后,它似乎有效
原始问题:
我正在尝试使用 dup2 来:
- 将“ls -al”的输出作为输入传递给“grep foo”,
- 其输出成为“grep bar”的输入",
- 最终输出到标准输出。
最终输出是(blank),文件“in”是(blank) &文件“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);
}
After incorporating Ben Voigt's answer into the code, it appears to work
Original question:
I'm trying to use dup2 to:
- pass the output of "ls -al" as input to "grep foo",
- whose output becomes input for "grep bar",
- which finally outputs to stdout.
The final output is (blank), the file "in" is (blank) & the file "out" has the output of "ls -al".
Any ideas what could be happening?
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
open
调用会在“in”中创建一个空文件,并且没有程序写入该文件,因此这是预期的。由于grep
的两个实例都是从空文件中读取的,因此它们的输出也是空的。您真正想要的是使用
pipe
函数获取一对句柄,将其写入一个程序并由下一个程序读取。您需要调用它两次,因为子进程之间有两组连接。Your
open
call creates an empty file "in" and none of the programs write to it, so that's expected. Since both instances ofgrep
read from an empty file, their output is also empty.What you really want is to use the
pipe
function to get a pair of handles, which is written to be one program and read from by the next. You'll need to call it twice because you have two sets of connections between child processes.