我是初学者,我还在开始学习 C 中的叉子和管道。
我正在尝试创建一个父进程和一个子进程,它们反复将变量传递给另一个。
parent1发送a,b --> child1计算a+b=c --> parent1接收c并计算c * 10000=X,然后发送p,q --> child1计算p+q=s--> parent 1接收s,计算s * 10000=Y --> 退出父子进程 --> 系统计算X+Y=Z,返回Z
我知道如何保持分叉并获得相同的父进程但不同的子进程。我基本上重复了下面的代码多次打开新的管道和分支(pid1、pid2、pid 3、pid 4 等和 port1、port2、端口 3、端口 4 等),所以父母是一样的,但新的孩子是已创建。
int port1[2];
if (pipe(port1) == -1){
printf("Error occurred with opening first pipe.");
return 1;
}
int pid1 = fork();
if (pid1 == 0){
close(port1[0]);
c = a+b;
if (write(port1[1], &c, sizeof(c)) == -1){
printf("Error occurred writng to the pipe.");
return 2;
}
close(port1[1]);
exit(EXIT_SUCCESS);
}
else{
close(port1[1]);
read(port1[0], &c, sizeof(c));
X = c * 10000;
close(port1[0]);
}
但是我如何多次从父母传给同一个孩子?
在程序开始时分叉一次,然后在每个分支中循环。