出于学习目的,我用 fork 和管道制作的简单程序有问题。我想要一个将 ppid 发送给父级的子级以输出 ppid 的值并执行两次。但是结果是两个ppid输出是一样的,为什么呢?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd[2]; /* for the pipe */
int n,pid,ppid,val;
int p[5],q[5];
if (pipe(fd) < 0) {
printf("Pipe creation error\n");
exit(1);
}
for(val=0;val<2;val++){
pid = fork();
if (pid < 0) {
printf("Fork failed\n");
exit(1);
} else if (pid == 0) { /* child */
ppid = getpid();
printf("child %d pid:%d \n",val+1,ppid);
write(fd[1], &ppid, sizeof(ppid));
sleep(1);
close(fd[1]);
} else { /* parent */
//printf("Parent: pid: ");
close(fd[1]);
printf("%d \n",val+1);
sleep(1);
n = read(fd[0], &ppid ,sizeof(ppid));
printf("%d \n",ppid);
// fflush(stdout);
close(fd[0]);
wait(NULL);
// printf("<parent> I have completed!\n");
exit(0);
}
}
}
最佳答案
程序设计可能存在潜在问题。因为 parent 在等待 child 在第一次迭代中,子进程对 val=1 执行 for 循环并生成另一个进程 通过 fork 。最终会出现三个进程,其中两个进程具有相同的pid 因为其中之一正在执行 for 两次。
关于C Pipe() 和 fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638062/