Linux使用c中的两个管道传递父进程和子进程之间的值?

时间:2014-02-10 02:58:02

标签: c linux process pipe

我在使用两个管道在父进程和子进程之间传递值时遇到问题..下面的代码可以工作,但结果不是我想要的。需要帮助来解决它。我希望这两个进程并行工作(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;
}

1 个答案:

答案 0 :(得分:1)

你在循环的第一次迭代中关闭路径,然后你将再次执行循环...这次在你的I / O操作上接收错误并且在另一端尝试读取时没有变化result。您可以进行两项更改:

首先,在I / O调用上添加正确的错误检查,以便您可以了解此类问题。通常,如果函数有错误,则返回-1(但请查看其文档以确定)。

然后......停止关闭您仍打算使用的管道!循环后关闭它们。

相关问题