执行后关闭(管道[1])

标签 c pipe exec

我有一根 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/

相关文章:

c - 为什么需要execstack才能在堆上执行代码?

Ubuntu 下的 C - 尝试解决 "Wheel game"时未出现预期结果

c - 如何检测客户端内部的pclose

c++ - 打开程序的管道并将其放入标准输入

c - Fork-server 和 exec 的孙子

c - 回复 udp 数据包被阻止

c - 位级运算符

c - 当我使用 SetWindowsHookEx WH_KEYBOARD_LL 交换键时,为什么我的程序会进入键盘输入事件过多的循环?

delphi - 在Delphi中启动两个进程并用管道连接它们

C - execvp 无法使用有效输入