C管道()和叉()的连接
我有一个简单的程序,我用叉子和管道学习目的的问题。我想要一个将ppid发送给父级的子级输出ppid的值,并执行两次。但是,结果是两个ppid输出是相同的。为什么C管道()和叉()的连接,c,C,我有一个简单的程序,我用叉子和管道学习目的的问题。我想要一个将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,ppi
#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);
}
}
}
#包括
#包括
#包括
#包括
int main()
{
int fd[2];/*用于管道*/
int n,pid,ppid,val;
int p[5],q[5];
如果(管道(fd)<0){
printf(“管道创建错误\n”);
出口(1);
}
对于(val=0;val),程序设计中可能存在潜在问题。因为父级等待子级
在第一次迭代中,子进程执行val=1的for循环,并生成另一个进程
最终有三个进程,其中两个进程的pid相同
因为其中一个正在执行两次。Huh?您正在通过管道将一个值从子对象发送到父对象,并将其打印出来;当然,它与子对象中的值完全相同。我觉得这个程序很好。可能会产生混淆:您要发送pid还是ppid?这个问题也非常类似于另一个具有类似nam的问题E