Zaid Munir
Zaid Munir

Reputation: 19

Read Write misbehaving with pipes

I have this standard piece of code which refuses to run correctly. The read always returns zero. The write call seems to get stuck and never returns. I have tried changing the order of parent and child but does not seem to work. I fail to figure out whats wrong. A bug perhaps?? Help would be appreciated.

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define READ_END 0
#define WRITE_END 1

int main()
{
  int pid;//,bytes;
  pid=fork();
  char buffer[100];
  char msg[]="Hello";
  //const char *msg2="Hi";
  int fd[2];
  //int p2[2];

  /* create the pipe */
  if (pipe(fd) == -1) 
  {
    fprintf(stderr,"Pipe failed");
    return 1;
  }


  if (pid < 0) 
  { /* error occurred */
    fprintf(stderr, "Fork Failed");
    return 1;
  }
  if (pid > 0) 
  { /* parent process */
    /* close the unused end of the pipe */
    close(fd[WRITE_END]);
    /* read from the pipe */
    int bytesRead = read(fd[READ_END], buffer, 100);
    printf("read %d",bytesRead);
    /* close the write end of the pipe */
    close(fd[READ_END]);
    wait(NULL);
  }
  else 
  { 
    /* child process */
    /* close the unused end of the pipe */
    close(fd[READ_END]);
    /* write to the pipe */
    int bytesWritten = write(fd[WRITE_END], msg, strlen(msg)+1);
    printf("%d",bytesWritten);
    /* close the write end of the pipe */
    close(fd[WRITE_END]);


  }

  return 0;

}

Upvotes: 0

Views: 67

Answers (1)

mgarciaisaia
mgarciaisaia

Reputation: 15610

You're forking before creating the pipe, so you are indeed creating two pipes (four file descriptors).

So, the fd[READ_END] in one of the two process isn't related anyhow with the fd[WRITE_END] in the other process.

It has helped me to run system("ls -l /proc/$$/fd/") in each process to see how the pipes are working.

Upvotes: 1

Related Questions