[英]communication between parent and child through pipe
I want a program where the parent and child talk each other.我想要一个父母和孩子互相交谈的程序。 so the output would be:
所以输出将是:
and so on.....等等.....
Below there is an example of code where the output makes first talk the parent and after the childs.下面是一个代码示例,其中输出首先与父级对话,然后在子级对话。 How can I correct the code?
如何更正代码?
for(int i=0; i<N; i++){
pid=fork();
if(pid==-1){
perror("fork\n");
exit(EXIT_FAILURE);
}
else if(pid==0){
srand(time(NULL));
int c;
read(fd[i][0], &c, 1);
printf("c: value: %d\n", c);
char word[c];
read(fd[i][0],&word, sizeof(word));
printf("c: word: %s\n", word);
int sum;
sum=c*i;
write(fd[i][1], &sum, sizeof(int));
printf("c: sended %d\n", sum);
int flag=0;
printf("flag :%d\n", flag);
read(fd[i][0], &flag, sizeof(int));
printf("c: flag= %d ->exit\n", flag);
exit(1);
}else{
int c;
c=rand()%100+1;
write(fd[i][1], &c, sizeof(int));
printf("p: value: %d\n", c);
char word[c];
write(fd[i][1], &word, sizeof(word));
printf("p: word: %s\n", word);
int sum;
read(fd[i][0], &sum, sizeof(int));
printf("p: sum is: %d\n", sum);
int flag=1;
write(fd[i][1], &flag, sizeof(int));
printf("par: flag exit %d\n", flag);
wait(NULL);
}
}
To have duplex communication between two processes, you need two<\/em> pipes:要在两个进程之间进行双工通信,您需要两个<\/em>管道:
If you use the same pipe for both, then you can end up with a situation like the child writing something to the pipe, and directly read it back again (and the parent will never see the data).如果您对两者都使用相同的管道,那么您最终可能会遇到这样的情况,例如孩子向管道写入内容,然后直接再次读回(并且父级将永远看不到数据)。
This could for example happen with eg例如,这可能发生在例如
write(fd[i][1], &sum, sizeof(int)); \/\/ ... \/\/ Could read sum that was written just above in the same process read(fd[i][0], &flag, sizeof(int));<\/code><\/pre>
in your child process.在您的子进程中。
For the example of the
write<\/code> and
read<\/code> calls shown above, you could have something like:
对于上面显示的
write<\/code>和
read<\/code>调用示例,您可能有如下内容:
int parent_to_child[2]; \/\/ Pipe where parent process write and child reads int child_to_parent[2]; \/\/ Pipe where parent process reads and child writes pipe(parent_to_child); pipe(child_to_parent); \/\/ ... pid = fork(); if (pid == 0) { \/\/ Other code... \/\/ Child writes to parent write(child_to_parent[1], &sum, sizeof(int)); \/\/ Child reads from parent read(parent_to_child[0], &flag, sizeof(int)); \/\/ ... } else { \/\/ Other code... \/\/ Parent reads from child read(child_to_parent[0], &sum, sizeof(int)); \/\/ Parent writes to child write(parent_to_child[1], &flag, sizeof(int)); \/\/ ... }<\/code><\/pre>"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.