MOHAMED
MOHAMED

Reputation: 43518

How to check if the pipe is opend before writing?

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?

Upvotes: 5

Views: 8873

Answers (1)

cnicutar
cnicutar

Reputation: 182629

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");

Upvotes: 8

Related Questions