(Unnamed) Pipe (POSIX)

… is user for unidirectional inter process communication on a single machine.


In the following example a pipe gets created for a communication from the child to the parent.

Source code

#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <iostream>

int main()
{
  int pipefd[2]; // pipefd[0] ... read, pipefd[1] ... write
  pipe(pipefd);
  pid_t pid = fork();

  if (pid == -1)
  {
    /* Couldn't fork */
    std::cout << "Couldn't fork" << std::endl;
  }
  else if (pid == 0)
  {
    /* Child process */
    close(pipefd[0]); // close read end
    dup2(pipefd[1], 1); // redirect write end to stdout
    close(pipefd[1]); // close origin write end
    execlp("./child.out", "child.out", NULL ); // returns only in error case
    std::cout << "Exec failed with: " << errno << std::endl;
  }
  else
  {
    /* Parent process */
    close(pipefd[1]); // close write end
    char buf[1024];
    while (read(pipefd[0], buf, sizeof(buf)) > 0)
    {
      std::cout << "My child said: " << buf << std::endl;
      memset(buf, 0, sizeof(buf));
    }
    close(pipefd[0]); // close unecessary read end
  }

  return 0;
}
#include <unistd.h>
#include <iostream>

int main()
{
  std::cout << "Hold" << std::endl;
  sleep(1);
  std::cout << "my" << std::endl;
  sleep(1);
  std::cout << "beer" << std::endl;

  return 0;
}

Output

$ ./main.out 
My child said: Hold

My child said: my

My child said: beer

File descriptors

   Parent          |   Child 
---------------------------------------
   0   stdin       |   0   stdin 
   1   stdout      |   1   pipefd[1]
   3   stderr      |   2   pipefd[1]
   ...             |   ...
   X   pipefd[0]   |
   ...             |
---------------------------------------