【问题标题】:Linux pass value between parent process and child process using two pipes in c?Linux使用c中的两个管道在父进程和子进程之间传递值?
【发布时间】: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;
}

【问题讨论】:

    标签: c linux process pipe


    【解决方案1】:

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

    首先,在您的 I/O 调用中添加适当的错误检查,以便您能够意识到此类问题。通常,如果函数有错误,则返回 -1(但请查看它们的文档以确定)。

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

    【讨论】:

    • 感谢您的评论。所以我需要在循环后关闭两个管道(读/写)吗?
    • 在循环之前关闭你永远不需要的管道和在循环之后完成的管道是公平的。这将使代码比现在更难看,并且在循环之后简单地关闭它们并没有错。 (当您退出时,您甚至可以让操作系统为您关闭它们,但这不是养成习惯的好模式。)
    • 我尝试将所有结束语句放在循环之后,但它不起作用。
    猜你喜欢
    • 2014-03-07
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多