Pipes between child processes in C

后端 未结 4 2030
旧时难觅i
旧时难觅i 2021-01-03 17:24

I\'ve seen this question before, but still a bit confused: how would I create communication between child processes of the same parent? All I\'m trying to do at the moment i

4条回答
  •  醉酒成梦
    2021-01-03 17:47

    The code to setup a pipe and have stadin/stdout redirected to the pipe is.

    In parent (before fork)

       int p[2];
       pipe(p);
    

    In the child (after fork) to get the pipe as stdin

       close(0);
       dup(p[0]);
    

    In the child (after fork) to get the pipe as stdout

      close(1);
      dup(p[1]);
    

    You can start writing to the pipe as soon as it is created. However this child process which is writing to the pipe will pause as soon as the pipe-buffer is filled and until the other process is starting reading from the pipe.

    Also look at the popen call as that may actually be a simpler version of what you need.

提交回复
热议问题