【问题标题】:close(pipe[1]) after exec执行后关闭(管道 [1])
【发布时间】:2015-07-02 08:32:17
【问题描述】:

我有一根烟斗。

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(),现在一切正常。

【问题讨论】:

  • 你能把整个源码发出来吗

标签: c pipe exec


【解决方案1】:

如果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*)。因为是变参函数,所以不会自动转换类型。

【讨论】:

  • 但是当它关​​闭时它的输出如何被重定向到管道中呢?
  • 因为你把它复制到了 FD 1,它仍然是打开的。
  • 好吧,但不幸的是,这仍然不能解决我的非终止进程 B 的问题。
  • @JohannesKlaus 那么你需要提供一个Minimal Complete Verifiable Example
  • 进程B挂在哪里?我没有看到循环,为什么它没有终止?
猜你喜欢
  • 1970-01-01
  • 2020-02-17
  • 2012-06-01
  • 2021-02-28
  • 2023-04-10
  • 2015-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多