C program to demonstrate fork() and pipe()

CServer Side ProgrammingProgramming

In this problem, we will demonstrate fork() and pipe(). Here we will create a C program for Linux that will concatenate two string, using 2 processes one will take input and send it to others which will concatenate the string with a predefined string and return the concatenated string.

First lets recap fork() and pipe()

fork() − it creates a child process, this child process ahs a new PID and PPID.

pipe() is a Unix, Linux system call that is used for inter-process communication.

Let’s take an example for understanding the problem,

Input

Learn programming
Predefined string: at tutorialspoint

Output

Learn programming at tutorialspoint

Explanation

P1 take input of string “learn programming”

Sends it to P2 using the pipe.

P2 concatenates the strings and sends back to p1 which prints it.

In the program, we will create two processes, say P1 and P2 using the fork() function. It has the following three return values which show the state of the program.

return value < 0, process creation failed.

return value = 0, child process.

return value > 0, which will be the process ID of the child process to the parent process i.e. The parent process will be executed.

We will create two pipes one for communicating from P1 to P2 and other from P2 to P1 as the pipe is one way.

C program to demonstrate fork() and pipe()

Example

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
#include<sys/wait.h>
int main(){
   int p12[2];
   int p21[2];
   char fixed_str[] = " at tutorialspoint";
   char input_str[100];
   pid_t P;
   if (pipe(p12)==-1 || pipe(p21)==-1 ){
      fprintf(stderr, "Filed to create pipe" );
      return 1;
   }
   scanf("%s", input_str);
   P = fork();
   if (P < 0){
      fprintf(stderr, "fork Failed" );
      return 1;
   }
   else if (P > 0){
      char concat_str[100];
      close(p12[0]);
      write(p12[1], input_str, strlen(input_str)+1);
      close(p12[1]);
      wait(NULL);
      close(p21[1]);
      read(p21[0], concat_str, 100);
      printf("Concatenated string %s\n", concat_str);
      close(p21[0]);
   }
   else{
      close(p12[1]);
      char concat_str[100];
      read(p12[0], concat_str, 100);
      int k = strlen(concat_str);
      int i;
      for (i=0; i<strlen(fixed_str); i++)
      concat_str[k++] = fixed_str[i];
      concat_str[k] = '\0';
      close(p12[0]);
      close(p21[0]);
      write(p21[1], concat_str, strlen(concat_str)+1);
      close(p21[1]);
      exit(0);
   }
}

Output

Concatenated string Learn at tutorialspoint
raja
Published on 17-Jul-2020 16:15:37
Advertisements