在兩個過程之間建立管道的情況下,如果這兩個人有兄弟關係而不是父親關係,他們會更容易出錯嗎?兄弟兄弟比父親孩子更安全嗎?
我給這個問題出現了,當我調查下面的代碼例如:
#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,退出也不會損害另一個兄弟。
因此,父親孩子可以導致這些情況,而兄弟之間的兄弟管不能因爲父親會等待他的兩個孩子(兄弟),因此第二個更安全 – pgmank