In this section we shall see how we can share variables and objects between processes
We are going to create an object in the child process and show that information in the main thread
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MAX_LIMIT 20
struct Person{
char name[MAX_LIMIT];
int age;
};
void disp(struct Person);
void getData(struct Person*);
int main(int argc, char *argv[]){
int pipefd[2];
if(pipe(pipefd) == -1)
printf("Error creating pipe\n");
int pid = fork();
// child process
if(pid == 0){
struct Person p1 = {0};
getData(&p1);
return write(pipefd[1], &p1, sizeof(p1));
}
// main thread
else{
wait(NULL);
struct Person p2 = {0};
if(read(pipefd[0], &p2, sizeof(p2)) == -1)
printf("Error reading data from file\n");
else
disp(p2);
}
close(pipefd[0]);
close(pipefd[1]);
return 0;
}
void getData(struct Person* p){
printf("Enter Name : ");
fflush(stdin);
fgets(p->name, MAX_LIMIT, stdin);
p->name[strlen(p->name)-1] = 0;
printf("Enter age: ");
scanf("%d",&(p->age));
}
void disp(struct Person p){
printf("\n%s is %d years old\n",p.name,p.age);
}
Output
Enter Name : Saptarshi Dey
Enter age: 21
Saptarshi Dey is 21 years old
How does the pipe() function work?
The pipe() function creates a pipe, a unidirectional data channel that can be used for inter-process communication. The array pipefd is used to return two file descriptors referring to the ends of the pipe. pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe. Data written to the write end of the pipe is buffered by the kernel until it is read from the read end of the pipe.