top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How are Pipes in Linux, how to create them and what is the difference between half duplex and full duplex pipes?

+4 votes
1,329 views

Please explain with C example code?

posted Sep 22, 2015 by Mishthy Mukherjee

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Pipe is a symbol used to provide output of one command as input to another command. The output of the command to the left of the pipe is sent as input to the command to the right of the pipe. The symbol is |.
Pipes are useful to chain up several programs, so that multiple commands can execute at once without using a shell script.

how to create?

Creates a pipe using pipe() system call. pipe create two file descriptor fd[0] and fd[1]. fd[0] refers to the read end of the pipe. fd[1] refers to the write end of the pipe.

To create a simple pipe with C, we make use of the pipe() system call. It takes a single argument, which is an array of two integers, and if successful, the array will contain two new file descriptors to be used for the pipeline. After creating a pipe, the process typically spawns a new process (remember the child inherits open file descriptors).

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        char    string[] = "Hello, world!\n";
        char    readbuffer[80];

        pipe(fd);

        if((childpid = fork()) == -1)
        {
                perror("fork");
                exit(1);
        }

        if(childpid == 0)
        {
                /* Child process closes up input side of pipe */
                close(fd[0]);

                /* Send "string" through the output side of pipe */
                write(fd[1], string, (strlen(string)+1));
                exit(0);
        }
        else
        {
                /* Parent process closes up output side of pipe */
                close(fd[1]);

                /* Read in a string from the pipe */
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                printf("Received string: %s", readbuffer);
        }
        return(0);
}

the difference between half duplex and full duplex pipes?

Half-Duplex allows for communication in one direction at one time then can switch to the opposite direction.
Full-Duplex allows for communication in either direction at any time.
Historically, pipes have been half duplex (i.e., data flows in only one direction). Some systems now provide full-duplex pipes.

answer Jul 30, 2016 by Mahedra Chaudhari
...