Pipe

Pipe provides a one-way flow of data, where the output of a process is directed into the input of another, which can be created using pipe() #Unix System Call. Pass in a file descriptor array (of type int) with a size of 2, the system call will return 2 file descriptors for use: fd[0] for reading and fd[1] for writing. A typical use case of Pipe is to establish a communication channel# between two related processes. The maximum amount of data allowed in the pipe (OS treats it like a Queue#) is usually 5120 bytes. In #unix, Pipe is implemented using #Unix Domain Sockets.

Note: Since Pipe has no name, only processes that are related (having a common parent) can create a pipe between them.

The following source code shows that a parent process initialised a Pipe then creates a child process which inherits the Pipe from its parent. The parent close the read end of the Pipe whereas the child will close the write end of the Pipe:

int childipd, pipe[2]

if (pipe(pipe1) < 0) < 0) {
  perror("pipe");
  exit(1);
}

if ((childpid = fork()) < 0) {
  perror("fork");
  exit(1);
} else if (childpid > 0 {
  close(pipe[1]); // close write end of the pipe for child

  // Do stuffs...

  close(pipe[0]); // close pipe for child
} else {
  close(pipe[0]); // close read end of the pipe for parent

  // Do stuffs...

  close (pipe[1]); // close pipe for parent
}

Note: If the queue is empty or is full, the read or write operation will be blocked respectively until there is information coming in to the pipe.

Other than using POSIX interface, we could utilise the support of Pipe by using the function popen() and pclose from the standard I/O library (stdio.h) in C which could be used as follows:

FILE *fp;

fp = popen(command, mode);  // create pipe
                            // mode as in "r" or "w", stand as read and write
                            // respectively

pclose(fp);                 // close pipe
Links to this page
#operating-system #) #unix