我有一根 pipe 。
int anotherPipe[2];
make(anotherPipe);
以下两个进程都可以访问此管道。
流程A:
close(anotherPipe[0]);
dup2(anotherPipe[1], 1); //redirect stdout to pipe
execl("/usr/bin/who", "usr/bin/who", NULL);
close(anotherPipe[1]); //this is never executed
流程B:
close(anotherPipe[1]);
read(anotherPipe[0], stringbuffer, bytestoread);
printf("%s\n", buffer);
printf("checkpoint\n");
close(anotherPipe[0]);
execl 中的“who”命令的输出通过管道重定向到进程 B,并在其中打印。但现在我的进程 B 没有终止,尽管检查点已打印。
“不终止”是指终端中不显示以下内容:
myusername@ubuntucomputer:~$
这里发生了什么以及如何解决?
编辑:解决了非终止进程 B 的问题。它终止了,但我的顶级进程在 A 和 B 之前完成,所以
myusername@ubuntucomputer:~$
打印得更早。我使用了 waitpid(),现在一切都很好。
最佳答案
如果execl()
成功,则原始程序中的它后面的任何内容都不会运行,因为它会用您要求它运行的程序替换进程的内容。您需要在 execl
之前关闭管道:
close(anotherPipe[0]);
dup2(anotherPipe[1], 1); //redirect stdout to pipe
close(anotherPipe[1]);
execl("/usr/bin/who", "usr/bin/who", (char*)NULL);
此外,在调用 execl
时,不要忘记将 NULL
更改为 (char*)
。由于它是一个变量参数函数,因此不会自动转换类型。
关于执行后关闭(管道[1]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29835594/