5

如果我向封闭的管道写一条消息,那么我的程序就会崩溃

if (write(pipe, msg, strlen(msg)) == -1) {
    printf("Error occured when trying to write to the pipe\n");
}

在我写信之前如何检查它pipe是否仍然打开?

4

1 回答 1

8

正确的方法是测试返回码,write然后检查errno

if (write(pipe, msg, strlen(msg)) == -1) {
    if (errno == EPIPE) {
        /* Closed pipe. */
    }
}

但是等等:写入一个封闭的管道不仅返回 -1 errno=EPIPE,它还发送一个SIGPIPE终止你的进程的信号:

EPIPE fd 连接到读取端关闭的管道或套接字。当这种情况发生时,写入过程也会收到一个 SIGPIPE 信号。

因此,在测试开始之前,您还需要忽略SIGPIPE

if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
    perror("signal");
于 2013-09-26T06:29:47.603 回答