If I write a message to a closed pipe then my program crash
if (write(pipe, msg, strlen(msg)) == -1) {
printf("Error occured when trying to write to the pipe\n");
}
how to check if pipe
is still opened before I writing to it?
pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.
A SIGPIPE is sent to a process if it tried to write to a socket that had been shutdown for writing or isn't connected (anymore). To avoid that the program ends in this case, you could either. make the process ignore SIGPIPE. #include <signal.
The correct way is to test the return code of write
and then also check errno
:
if (write(pipe, msg, strlen(msg)) == -1) {
if (errno == EPIPE) {
/* Closed pipe. */
}
}
But wait: writing to a closed pipe no only returns -1 with errno=EPIPE
, it also sends a SIGPIPE
signal which terminates your process:
EPIPE fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIGPIPE signal.
So before that testing works you also need to ignore SIGPIPE
:
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
perror("signal");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With