Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Pass the value from child process to parent process

  • Last Updated : 06 Dec, 2019

Prerequisite: Pipe() and Fork() Basic
Write a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print it in the parent process.

Examples: Suppose we have an array a[]={1, 2, 3, 4, 5} in child process, then output should be 1 2 3 4 5.

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

Input:  1 2 3 4 5
Output: 1 2 3 4 5




// C program for passing value from
// child process to parent process
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h> 
#include <stdlib.h> 
#include <sys/wait.h>
#define MAX 10
  
int main()
{
  
  int fd[2], i = 0;
  pipe(fd);
  pid_t pid = fork();
  
   if(pid > 0) {
      wait(NULL);
  
      // closing the standard input 
      close(0);
  
      // no need to use the write end of pipe here so close it
      close(fd[1]); 
  
       // duplicating fd[0] with standard input 0
      dup(fd[0]); 
      int arr[MAX];
  
      // n stores the total bytes read successfully
      int n = read(fd[0], arr, sizeof(arr));
      for ( i = 0;i < n/4; i++)
  
         // printing the array received from child process
          printf("%d ", arr[i]); 
  
  else if( pid == 0 ) {
      int arr[] = {1, 2, 3, 4, 5};
  
      // no need to use the read end of pipe here so close it
      close(fd[0]); 
  
       // closing the standard output
      close(1);    
  
      // duplicating fd[0] with standard output 1
      dup(fd[1]);  
      write(1, arr, sizeof(arr));
  
  
  else {
      perror("error\n"); //fork()
  }

Steps for executing above code:

  • To compile, write gcc program_name.c
  • To run, write ./a.out



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!