Interprocess Communication
pipe
  • 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
  • #include <stdio.h> 
    #include <unistd.h> 
    #include <stdlib.h>
    
    #define MSGSIZE 16 
    
    char* msg = "hello, world!"; 
    
    int main() 
    { 
        char inbuf[MSGSIZE]; 
        int p[2], i; 
      
        // create a pipe
        if (pipe(p) < 0) 
            exit(1); 
      
        // write message to pipe
        write(p[1], msg, MSGSIZE); 
      
        // read message from pipe
        read(p[0], inbuf, MSGSIZE); 
        printf("%s\n", inbuf); 
    
        return 0; 
    } 
    		

    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/wait.h>
    
    int main()
    {
        int pipefd[2]; // 0, read; 1, write
        pid_t fpid;
    
        char buf[100];
    
        if(pipe(pipefd) < 0)
        {
            printf("Cannot create pipe ...");
            exit(1);
        }
    
        fpid = fork();
    
        if(fpid == 0)
        {
            printf("I am the child process %d, child id is: %d\n", getpid(), fpid);
    
            close(pipefd[1]); //close the write-end of the child process
            wait(NULL);
            read(pipefd[0], buf, 100);
            write(1, buf, strlen(buf)+1);
            write(1, "\n", 1);
            close(pipefd[0]); //close the read-end of the child process
            exit(0);
        }
        else
        {
            printf("I am the parent process %d, parent id is: %d\n", getpid(), fpid);
    
            close(pipefd[0]); //close the read-end of the parent process
            char str[] = "Hello World!";
            write(pipefd[1], str, strlen(str));
            close(pipefd[1]); //close the write-end of the child process
            wait(NULL);
            exit(0);
        }
    
        return 0;
    }
    		
    Reference
  • geeksforgeeks