I have the following code:
int fds[2];
if (pipe(fds) < 0) {
fprintf(stderr, "ERROR, unable to open pipe: %s\n", strerror(errno));
}
if (fcntl(fds[0], F_SETFL, O_NONBLOCK) < 0) {
fprintf(stderr, "ERROR, unable make read end non-blocking: %s\n", strerror(errno));
}
pid_t pid1 = fork();
if (pid1 == 0) {
if (close(fds[0]) < 0) {
fprintf(stderr, "ERROR, unable to close read end of pipe: %s\n", strerror(errno));
}
// go on to write something
}
pid_t pid2 = fork();
if (pid2 == 0) {
if (close(fds[1]) < 0) {
fprintf(stderr, "ERROR, unable to close write end of pipe: %s\n", strerror(errno));
}
// go on to read something
}
if (close(fds[1]) < 0) {
fprintf(stderr, "ERROR, unable to close write end of pipe in main process: %s\n", strerror(errno));
}
if (close(fds[0]) < 0) {
fprintf(stderr, "ERROR, unable to close read end of pipe in main process: %s\n", strerror(errno));
}
I get the error message "ERROR, unable to close write end of pipe in main process: Bad file descriptor". I was under the impression that you should close each end of a pipe in any process which doesn't use that end. The main process does not use the pipe here. It exists only to allow the two children to communicate. In addition, there are no other errors on any of the other calls to close(). I don't understand why the parent process can't close only the write end of the pipe.