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; 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 succesfully 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() } } |
chevron_right
filter_none
Steps for executing above code:
- To compile, write gcc program_name.c
- To run, write ./a.out
Recommended Posts:
- Exit status of a child process in Linux
- Process Table and Process Control Block (PCB)
- Process states and Transitions in a UNIX Process
- Using fork() to produce 1 parent and its 3 child processes
- Process Synchronization | Set 2
- Communication between two process using signals in C
- Get/Set process resource limits in C
- Semaphores in Process Synchronization
- Inter Process Communication (IPC)
- Monitors in Process Synchronization
- Introduction of Process Synchronization
- Introduction of Process Management
- Difference between Process and Thread
- Process Schedulers in Operating System
- Bakery Algorithm in Process Synchronization
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.



