πSharing information between processes
In this section we shall see how we can share variables and objects between processes
#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
How does the pipe() function work?
Last updated