【发布时间】:2015-09-29 22:03:19
【问题描述】:
在两个进程之间建立管道的情况下,如果这两个进程是兄弟关系而不是父子关系,会不会更容易出错?
当我调查下面的代码示例时,我提出了这个问题:
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
void runpipe();
int
main(int argc, char **argv)
{
int pid, status;
int fd[2];
pipe(fd);
switch (pid = fork())
{
case 0: /* child */
runpipe(fd);
exit(0);
default: /* parent */
while ((pid = wait(&status)) != -1) {
fprintf(stderr, "process %d exits with %d\n", pid, WEXITSTATUS(status));
exit(0);
}
case -1:
perror("fork");
exit(1);
}
exit(0);
}
char *cmd1[] = { "ls", "-al", "/", 0 };
char *cmd2[] = { "tr", "a-z", "A-Z", 0 };
void
runpipe(int pfd[])
{
int pid;
switch (pid = fork())
{
case 0: /* child */
dup2(pfd[0], 0);
close(pfd[1]); /* the child does not need this end of the pipe */
execvp(cmd2[0], cmd2);
perror(cmd2[0]);
default: /* parent */
dup2(pfd[1], 1);
close(pfd[0]); /* the parent does not need this end of the pipe */
execvp(cmd1[0], cmd1);
perror(cmd1[0]);
case -1:
perror("fork");
exit(1);
}
}
在上面的例子中,父母(爷爷)派生出一个孩子(父母),然后孩子又派生出另一个孩子(孙子)。爷爷等爸爸,但爸爸不等孙子,因为他们都执行 execvp。如果孩子早于父亲(僵尸)或父亲早于孩子(孤儿)完成,会发生什么?另一方面,如果我们有两个兄弟连接到管道和一个父亲并等待他们(总共三个进程),即使他们两个兄弟都执行了 execvp,一个退出也不会伤害另一个。
【问题讨论】:
标签: c unix process pipe child-process