【发布时间】:2014-02-10 02:58:01
【问题描述】:
我在使用两个管道在父进程和子进程之间传递值时遇到问题。下面的代码有效,但结果不是我想要的。需要帮助来修复它。我希望这两个进程并行工作(parent->child->parent->child),而不是(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;
}
【问题讨论】: