简体   繁体   English

执行后关闭(pipe [1])

[英]close(pipe[1]) after exec

I got a pipe. 我有烟斗。

int anotherPipe[2];
make(anotherPipe);

Both of the following processes have access to this pipe. 以下两个过程都可以访问此管道。

Process A: 流程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

Process B: 流程B:

close(anotherPipe[1]);
read(anotherPipe[0], stringbuffer, bytestoread);
printf("%s\n", buffer);
printf("checkpoint\n");
close(anotherPipe[0]);

The "who" command's output from execl is redirected to process B via pipe, where it is printed. execl的“谁”命令的输出通过管道重定向到进程B,并在此打印。 But now my process B is not terminating, although the checkpoint is printed. 但是现在我的过程B并没有终止,尽管检查点已打印出来。

By 'not terminating' I mean that the following is not displayed in the terminal: “不终止”是指终端中不显示以下内容:

myusername@ubuntucomputer:~$

What is happening here and how is it solved? 这里发生了什么,如何解决?

EDIT: Solved the issue with the non-terminating process B. It terminated, but my top level process finished before A and B, so the 编辑:解决了非终止过程B的问题。它终止了,但是我的顶级过程在A和B之前完成了,所以

myusername@ubuntucomputer:~$

was printed a lot earlier. 印刷得早得多。 I used waitpid() and now everything is fine. 我使用了waitpid(),现在一切都很好。

If execl() is successful, nothing after it in the original program runs, since it replaces the contents of the process with the program you ask it to run. 如果execl()成功,则原始程序中的execl()不会运行,因为它将用您要求其运行的程序替换进程的内容。 You need to close the pipe before 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);

Also, don't forget to case NULL to (char*) when calling execl . 另外,在调用execl时,不要忘记将NULL变为(char*) Since it's a variable-arguments function, it won't convert the type automatically. 由于它是一个变量参数函数,因此不会自动转换类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM