Open In App

pipe() System call

Last Updated : 15 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite : I/O System calls

Conceptually, a pipe is a connection between two processes, such that the standard output from one process becomes the standard input of the other process. In UNIX Operating System, Pipes are useful for communication between related processes(inter-process communication).

  • Pipe is one-way communication only i.e we can use a pipe such that One process write to the pipe, and the other process reads from the pipe. It opens a pipe, which is an area of main memory that is treated as a “virtual file”.
  • The pipe can be used by the creating process, as well as all its child processes, for reading and writing. One process can write to this “virtual file” or pipe and another related process can read from it.
  • If a process tries to read before something is written to the pipe, the process is suspended until something is written.
  • The pipe system call finds the first two available positions in the process’s open file table and allocates them for the read and write ends of the pipe.

  • Syntax in C language:

    int pipe(int fds[2]);
    
    Parameters :
    fd[0] will be the fd(file descriptor) for the 
    read end of pipe.
    fd[1] will be the fd for the write end of pipe.
    Returns : 0 on Success.
    -1 on error.

    Pipes behave FIFO(First in First out), Pipe behave like a queue data structure. Size of read and write don’t have to match here. We can write 512 bytes at a time but we can read only 1 byte at a time in a pipe.




    // C program to illustrate
    // pipe system call in C
    #include <stdio.h>
    #include <unistd.h>
    #define MSGSIZE 16
    char* msg1 = "hello, world #1";
    char* msg2 = "hello, world #2";
    char* msg3 = "hello, world #3";
      
    int main()
    {
        char inbuf[MSGSIZE];
        int p[2], i;
      
        if (pipe(p) < 0)
            exit(1);
      
        /* continued */
        /* write pipe */
      
        write(p[1], msg1, MSGSIZE);
        write(p[1], msg2, MSGSIZE);
        write(p[1], msg3, MSGSIZE);
      
        for (i = 0; i < 3; i++) {
            /* read pipe */
            read(p[0], inbuf, MSGSIZE);
            printf("% s\n", inbuf);
        }
        return 0;
    }

    
    

    Output:

    hello, world #1
    hello, world #2
    hello, world #3
    

    Parent and child sharing a pipe

    When we use fork in any process, file descriptors remain open across child process and also parent process. If we call fork after creating a pipe, then the parent and child can communicate via the pipe.

    Output of the following program.




    // C program to illustrate
    // pipe system call in C
    // shared by Parent and Child
    #include <stdio.h>
    #include <unistd.h>
    #define MSGSIZE 16
    char* msg1 = "hello, world #1";
    char* msg2 = "hello, world #2";
    char* msg3 = "hello, world #3";
      
    int main()
    {
        char inbuf[MSGSIZE];
        int p[2], pid, nbytes;
      
        if (pipe(p) < 0)
            exit(1);
      
        /* continued */
        if ((pid = fork()) > 0) {
            write(p[1], msg1, MSGSIZE);
            write(p[1], msg2, MSGSIZE);
            write(p[1], msg3, MSGSIZE);
      
            // Adding this line will
            // not hang the program
            // close(p[1]);
            wait(NULL);
        }
      
        else {
            // Adding this line will
            // not hang the program
            // close(p[1]);
            while ((nbytes = read(p[0], inbuf, MSGSIZE)) > 0)
                printf("% s\n", inbuf);
            if (nbytes != 0)
                exit(2);
            printf("Finished reading\n");
        }
        return 0;
    }

    
    

    Output:

    hello world, #1
    hello world, #2
    hello world, #3
    (hangs)         //program does not terminate but hangs
    

    Here, In this code After finishing reading/writing, both parent and child block instead of terminating the process and that’s why program hangs. This happens because read system call gets as much data it requests or as much data as the pipe has, whichever is less.

    • If pipe is empty and we call read system call then Reads on the pipe will return EOF (return value 0) if no process has the write end open.
    • If some other process has the pipe open for writing, read will block in anticipation of new data so this code output hangs because here write ends parent process and also child process doesn’t close.

    For more details about parent and child sharing pipe, please refer C program to demonstrate fork() and pipe().
     



Similar Reads

Difference Between Call by Value and Call by Reference in C
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters. The parameters passed to the function are called actual parameters whereas the parameters received by the function are called formal parameters. Call By Value in C In call by value
5 min read
C Program to Demonstrate fork() and pipe()
fork() is used to create a child process. This child process is a copy of the original(parent) process. It is the primary method of process creation on Unix-like operating systems.( See this article for reference). Syntax: fork(); // It does not take any parameter, it returns // integer values. It may return negative, // positive or zero integer va
4 min read
Named Pipe or FIFO with example C program
In computing, a named pipe (also known as a FIFO) is one of the methods for inter-process communication. It is an extension to the traditional pipe concept on Unix. A traditional pipe is "unnamed" and lasts only as long as the process.A named pipe, however, can last as long as the system is up, beyond the life of the process. It can be deleted if n
3 min read
Difference between system() and execl() call
A system() call is a way for the programs to interact with the operating system. It is used to execute a command within a process. The system call provides the services of the operating system to the user programs via Application Program Interface (API). It provides an interface between a process and an operating system and it does not replace the
4 min read
Wait System Call in C
Prerequisite : Fork System callA call to wait() blocks the calling process until one of its child processes exits or a signal is received. After child process terminates, parent continues its execution after wait system call instruction. Child process may terminate due to any of these: It calls exit();It returns (an int) from mainIt receives a sign
4 min read
Can We Call an Undeclared Function in C++?
Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn't list argument types.If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn't compile and generates errors. In
2 min read
Difference between CALL and JUMP instructions
CALL instruction is used to call a subroutine. Subroutines are often used to perform tasks that need to be performed frequently. The JMP instruction is used to cause the PLC (Programmable Logic Control) to skip over rungs. The differences Between CALL and JUMP instructions are: SERIAL NO. JUMP CALL 1. Program control is transferred to a memory loca
1 min read
How to call function within function in C or C++
When we begin programming in C/C++, we generally write one main() function and write all our logic inside this. This approach is fine for very small programs, but as the program size grows, this become unmanageable. So we use functions. We write code in the form of functions. The main function always acts as a driver function and calls other functi
3 min read
Tail Call Optimisation in C
In C programming, Tail Call Optimization (TCO) is a technique that eliminates the need for an additional stack frame to store the data of another function by reusing the current function's stack frame. This optimization technique is only possible for tail function calls. What is Tail Call?The tail call is the type of function call where another fun
4 min read
Is it possible to call constructor and destructor explicitly in C++?
A constructor is a special member function that is automatically called by the compiler when an object is created and the destructor is also a special member function that is also implicitly called by the compiler when the object goes out of scope. They are also called when a dynamically allocated object is allocated and destroyed, a new operator a
3 min read