views:

230

answers:

2

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);
}
+5  A: 

You can't do bi-directional synchronization on a single pipe.

You can do bi-directional synchronization on a Unix-domain socket.

Jonathan Leffler
Note that you can easily create a unix-domain socket that acts like a bidirectional pipe using the `socketpair()` call
bdonlan
+4  A: 

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).

sambowry