Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the pipe is opend before writing?

Tags:

c

linux

pipe

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?

like image 995
MOHAMED Avatar asked Sep 26 '13 06:09

MOHAMED


People also ask

Which end of pipe is read?

pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.

What is Sigpipe signal?

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.


1 Answers

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");
like image 86
cnicutar Avatar answered Oct 15 '22 18:10

cnicutar