Pass the value from child process to parent process

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.

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;
  pid_t pid = fork();
   if(pid > 0) {
      // closing the standard input 
      // no need to use the write end of pipe here so close it
       // duplicating fd[0] with standard input 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
       // closing the standard output
      // duplicating fd[0] with standard output 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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : nidhi_biet