When using pipes, we must be careful to close unused descriptors in order to ensure that reading processes detect end-of-file and writing processes receive the SIGPIPE signal or the EPIPE error.
在使用管道时,父进程创建了管道,然后再创建子进程时,父进程和子进程都保留了管道的读文件描述符和写文件描述符,所以如果想让管道的读操作能够读到EOF,父进程要关闭自己保留的写文件描述符
如下的管道测试代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int pipe_default[2];
int main(int argc, char *argv[]) {
pid_t pid;
char buffer[32];
memset(buffer, 0, 32);
if (pipe(pipe_default) < 0) {
printf("Failed to create pipe!\n");
return 0;
}
pid = fork();
printf("pid = %d\n", pid);
if (pid == 0) {
close(pipe_default[1]);
//sleep(5);
if (read(pipe_default[0], buffer, 32) > 0) {
printf("Received data from server, %s!\n", buffer);
}
close(pipe_default[0]);
}else {
close(pipe_default[0]);
char * contentToSend = "Hey, guy. Nice to meet you!!";
if (-1 != write(pipe_default[1], contentToSend, strlen(contentToSend))) {
printf("Send data to the other side\n");
}
close(pipe_default[1]);
wait(pid, NULL, 0);
}
return 1;
}