SIGPIPE signal handling

1.3k Views Asked by At

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.

0

There are 0 best solutions below