难以让两个进程通过管道进行通信并且替代地减去一个数字。
输出应该像: 过程1:9 过程2:8 process1:7 ......
到目前为止我做了什么:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int p2c[2];
int c2p[2];
int n = 9;
pipe(p2c);
pipe(c2p);
write(p2c[1], &n, sizeof(int));
if(fork() == 0) {
read(p2c[0], &n, sizeof(int));
printf("Got from parent: %d", n);
n--;
write(c2p[1], &n, sizeof(int));
close(p2c[0]);
close(p2c[1]);
close(c2p[0]);
close(c2p[1]);
exit(0);
}
else{
read(c2p[0], &n, sizeof(int));
printf("Got from child: %d", n);
n--;
write(p2c[1], &n; sizeof(int));
close(p2c[0]);
close(p2c[1]);
close(c2p[0]);
close(c2p[1]);
}
return 0;
}
输出结果: 来自父母:9 来自孩子:8 什么是让这两个过程将数字减去0的正确方法?
答案 0 :(得分:1)
有意义的是,你只能得到&#34; 得到父母:9得到孩子:8 &#34;因此,您需要为子和父进程提供 while 或 for 循环在减少 n 或写入结束后,您期望的是什么,并且这些循环的停止条件为(n <0)管道关闭:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int p2c[2];
int c2p[2];
int n = 9;
pipe(p2c);
pipe(c2p);
// this is important to prevent deadlock situation, at least one of both processes
// must start a write operation before while loop, unless the read will block and
// and each process still waiting the other to write something on the pipe
write(p2c[1], &n, sizeof(int));
if(fork() == 0) {
int readStatus;
while(1){
readStatus=read(p2c[0], &n, sizeof(int));
// when read returns 0, this means the write end of pipe was closed, so we have to break the loop
// because no more data to recieve
if(readStatus == 0) break;
printf("Got from parent: %d\n", n);
n--;
// we check if n less than 0, if yes we are finished
if(n < 0) break;
write(c2p[1], &n, sizeof(int));
}
close(p2c[0]);
close(p2c[1]);
close(c2p[0]);
close(c2p[1]);
exit(0);
}
else{
int readStatus;
while(1){
readStatus= read(c2p[0], &n, sizeof(int));
if(readStatus == 0) break;
printf("Got from child: %d\n", n);
n--;
if(n < 0) break;
write(p2c[1], &n, sizeof(int));
}
close(p2c[0]);
close(p2c[1]);
close(c2p[0]);
close(c2p[1]);
}
return 0;
}