[英]Linux pass value between parent process and child process using two pipes in c?
我在使用两个管道的父进程和子进程之间传递值时遇到麻烦。下面的代码有效,但结果不是我想要的。 需要帮助修复它。 我希望两个进程并行工作(父->子->父->子),而不是(partent-> child-> child-> child ..)
输出应如下所示:
初始值0
家长:
运算后的x值:1
儿童:
手术后x值:10
家长:
运算后的x值:11
儿童:
手术后x值:110
家长:
手术后x值:111
儿童
手术后x值:1110
家长:
手术后x值:1111
儿童
手术后x值:11110
但是,以下代码显示了输出:
初始值0
家长:
运算后的x值:1
儿童:
手术后x值:10
儿童:
手术后x值:100
儿童:
手术后x值:1000
儿童:
手术后x值:10000
儿童:
手术后x值:100000
家长:
运算后的x值:11
家长:
手术后x值:12
家长:
手术后的x值:13
家长:
手术后x值:14
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#define BUFFER_SIZE 25
#define READ 0
#define WRITE 1
int main(void)
{
pid_t pid;
//open two pipes, one for each direction
int mypipefd[2];
int mypipefd2[2];
int result=0;
int i;
printf("initial value %d\n",result);
/* create the pipe */
if (pipe(mypipefd) == -1 || pipe(mypipefd2) == -1) {
fprintf(stderr,"Pipe failed");
return 1;
}
/* now fork a child process */
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
}
for(i=0;i<5;i++){
if (pid > 0) { /* parent process */
result++;
close(mypipefd[READ]); //close read end, write and then close write end
write(mypipefd[WRITE],&result,sizeof(result)); //write to pipe one
printf("Parent:\n x value after operation: %d\n",result);
close(mypipefd[WRITE]); //close pipe one read
close(mypipefd2[WRITE]); //close pipe two write
read(mypipefd2[READ],&result,sizeof(result)); //read from pipe 2
close(mypipefd2[READ]); //close pipe two
wait(0);
}
else { /* child process */
close(mypipefd[WRITE]); //close write end, read, and then close read end
read(mypipefd[READ],&result,sizeof(result)); //read from pipe one
close(mypipefd[READ]); //close pipe one read
result*=10;
printf("child:\n x value after operation: %d\n", result);
close(mypipefd2[READ]); //close read end, write and then close write end
write(mypipefd2[WRITE],&result,sizeof(result));
close(mypipefd2[WRITE]);
}
}
return 0;
}
您将在循环的第一次迭代中关闭路径,然后再次执行循环...这次,您的I / O操作收到错误,并且尝试读取另一端的result
没有任何改变。 您需要进行两项更改:
首先,在您的I / O调用上添加适当的错误检查,以便您可以意识到此类问题。 通常,如果函数有错误,则返回-1(但是请确保参考其文档)。
然后...停止关闭您仍打算使用的管道! 循环后将其关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.