program for interprocess communication using pipes in c

Solutions on MaxInterview for program for interprocess communication using pipes in c by the best coders in the world

showing results for - "program for interprocess communication using pipes in c"
Isabella
11 Aug 2016
1#include<stdio.h>
2#include<unistd.h>
3
4int main() {
5   int pipefds1[2], pipefds2[2];
6   int returnstatus1, returnstatus2;
7   int pid;
8   char pipe1writemessage[20] = "Hi";
9   char pipe2writemessage[20] = "Hello";
10   char readmessage[20];
11   returnstatus1 = pipe(pipefds1);
12   
13   if (returnstatus1 == -1) {
14      printf("Unable to create pipe 1 \n");
15      return 1;
16   }
17   returnstatus2 = pipe(pipefds2);
18   
19   if (returnstatus2 == -1) {
20      printf("Unable to create pipe 2 \n");
21      return 1;
22   }
23   pid = fork();
24   
25   if (pid != 0) // Parent process {
26      close(pipefds1[0]); // Close the unwanted pipe1 read side
27      close(pipefds2[1]); // Close the unwanted pipe2 write side
28      printf("In Parent: Writing to pipe 1 – Message is %s\n", pipe1writemessage);
29      write(pipefds1[1], pipe1writemessage, sizeof(pipe1writemessage));
30      read(pipefds2[0], readmessage, sizeof(readmessage));
31      printf("In Parent: Reading from pipe 2 – Message is %s\n", readmessage);
32   } else { //child process
33      close(pipefds1[1]); // Close the unwanted pipe1 write side
34      close(pipefds2[0]); // Close the unwanted pipe2 read side
35      read(pipefds1[0], readmessage, sizeof(readmessage));
36      printf("In Child: Reading from pipe 1 – Message is %s\n", readmessage);
37      printf("In Child: Writing to pipe 2 – Message is %s\n", pipe2writemessage);
38      write(pipefds2[1], pipe2writemessage, sizeof(pipe2writemessage));
39   }
40   return 0;
41}