在写作之前如何检查管道是否开启?

MOH*_*MED 4 c linux pipe

如果我将消息写入已关闭的管道,那么我的程序会崩溃

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

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

cni*_*tar 7

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

if (write(pipe, msg, strlen(msg)) == -1) {
    if (errno == EPIPE) {
        /* Closed pipe. */
    }
}
Run Code Online (Sandbox Code Playgroud)

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

EPIPE fd连接到读取端关闭的管道或插座.当发生这种情况时,写入过程也将收到SIGPIPE信号.

因此,在测试工作之前,您还需要忽略SIGPIPE:

if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
    perror("signal");
Run Code Online (Sandbox Code Playgroud)