1

I'm trying to figure out how does a pipe communication between two related processes work, so I wrote this simple C program.

#define  READ   0
#define  WRITE  1

char*  phrase = "This is a message!!!";
char*  phrase2 = "This is a second message!!!";

char buffer[100];

void sigpipe_h(int sig0){       //SIGPIPE handler
    printf("Ricevuto SIGPIPE\n");
    signal(SIGPIPE, sigpipe_h);
}

int main()
{
int fd[2], bytesRead, bytesRead2;
signal(SIGPIPE, sigpipe_h);

pipe(fd);

pid_t pid = fork();

if(pid == 0){   //child
    write(fd[WRITE], phrase, strlen(phrase)+1);     //write
    sleep(2);
    write(fd[WRITE], phrase2, strlen(phrase2)+1);//i'm writing for the second time

    sleep(2);
    close(fd[WRITE]);   //write side closed
}
else {          //parent
    bytesRead = read(fd[READ], buffer, 100); //receive message
    printf("The process %d has received %d bytes: %s \n", getpid(), bytesRead, buffer );
    close(fd[READ]);   //read side closed

    sleep(4);

}

return 0;


}

I create a pipe, the child writes something on it, the parent read the message and closes the read side pipe. Until now it works perfectly, but when I try to send a second message, with the pipe closed at the read side, it should raise a SIGPIPE signal handled by my sigpipe_h function, doesn't it? Why it doesn't happen? Where am I wrong?

Thanks for the help.

88mdil
  • 43
  • 1
  • 8
  • 3
    The child has the pipe still open for reading. – ninjalj May 25 '14 at 23:40
  • @ninjalj is right. Works fine for me with this change. – chrk May 25 '14 at 23:47
  • possible duplicate of [i didn't close the one of the end of pipe,is there anything wrong happened?](http://stackoverflow.com/questions/10120473/i-didnt-close-the-one-of-the-end-of-pipe-is-there-anything-wrong-happened) – ninjalj May 25 '14 at 23:49
  • Also: http://stackoverflow.com/questions/11599462/what-happens-if-a-son-process-wont-close-the-pipe-from-writing-while-reading http://stackoverflow.com/questions/16005717/select-still-blocks-read-from-pipe – ninjalj May 25 '14 at 23:52
  • I thought that closing the read end of the reader was enough, now it works. Thank you ninjalj. – 88mdil May 25 '14 at 23:56

0 Answers0