c++linuxpipeforkdup

Requirements in forked child programs to have a pipe communication with the launcher program


Let's say that I have a program called "parent" who uses fork() and execl() to launch another program called "child" and I want to keep communications between this two programs. It seems that the best way to keep this communications would bee using unnamed pipes. It's easy to found documentation and examples about the requirements in the "parent" program side but I haven't found the same in the "child" side.

For example, I think this guide is good but don´t show what I have to do in the program launched whith exec in order to have communications between both programs, I have to use dup() in the "parent" to share the descriptors but who I do refer to the pipe correctly in the child side to establish a communication between both?: http://tldp.org/LDP/lpg/node11.html


Solution

  • In the article, the child process uses dup and dup2 (dup2 is better) to set up one of the file descriptors as standard input.
    The process is similar for standard output (you'll need a separate pipe and associated file descriptors).

    The parent can then communicate with the child's stdio by reading and writing to its end of the pipe(s).

    When the child is execed, these file descriptors are inherited, so the same pipe endpoints will remain standard input and output in the child process.

    In other words, if you set up the file descriptors with dup/dup2 like in the article, you don't need to do anything special in the execed process, you can just read and write on stdio.