我试图弄清楚两个相关进程之间的管道通信是如何工作的,所以我编写了这个简单的 C 程序。
#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;
}
我创建了一个管道,孩子在上面写了一些东西,父母阅读了消息并关闭了读取侧管道。到目前为止,它工作得很好,但是当我尝试发送第二条消息时,管道在读取端关闭,它应该引发一个由我的 sigpipe_h 函数处理的 SIGPIPE 信号,不是吗?为什么没有发生?我哪里错了?
谢谢您的帮助。