Is there any way to synchronize parent and child in C using one pipe in Unix?
-
07-07-2019 - |
Question
Suppose both parent and child use one pipe for writing and reading means when one writes then only other read otherwise it blocks. Is there any way to do it? I tried to do it with sleep function but due to race conditions, it does not give the correct output. This is my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define MSGSIZE 16
main ()
{
int i;
char *msg = "How are you?";
char inbuff[MSGSIZE];
int p[2];
pid_t ret;
pipe (p);
ret = fork ();
if (ret > 0)
{
i = 0;
while (i < 10)
{
write (p[1], msg, MSGSIZE);
sleep (2);
read (p[0], inbuff, MSGSIZE);
printf ("Parent: %s\n", inbuff);
i++;
}
exit(1);
}
else
{
i = 0;
while (i < 10)
{
sleep (1);
read (p[0], inbuff, MSGSIZE);
printf ("Child: %s\n", inbuff);
write (p[1], "i am fine", strlen ("i am fine"));
i++;
}
}
exit (0);
}
Solution
The pipe() creates two filedescriptor, one for reading and an another for writing. For two way communication, you need to create two pipes (four filedescriptors).
OTHER TIPS
You can't do bi-directional synchronization on a single pipe.
You can do bi-directional synchronization on a Unix-domain socket.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow