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.
Input: 1 2 3 4 5
Output: 1 2 3 4 5
#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);
close(0);
close(fd[1]);
dup(fd[0]);
int arr[MAX];
int n = read(fd[0], arr, sizeof (arr));
for ( i = 0;i < n/4; i++)
printf ( "%d " , arr[i]);
}
else if ( pid == 0 ) {
int arr[] = {1, 2, 3, 4, 5};
close(fd[0]);
close(1);
dup(fd[1]);
write(1, arr, sizeof (arr));
}
else {
perror ( "error\n" );
}
}
|
Steps for executing above code:
- To compile, write gcc program_name.c
- To run, write ./a.out
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...