【问题标题】:How to check if the pipe is opend before writing?写之前如何检查管道是否打开?
【发布时间】:2013-09-26 06:26:03
【问题描述】:

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

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

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

【问题讨论】:

    标签: c linux pipe


    【解决方案1】:

    正确的方法是测试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");
    

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 2017-06-23
      • 2012-07-02
      • 2015-06-17
      • 2015-02-14
      • 2013-04-25
      • 2014-12-09
      • 1970-01-01
      相关资源
      最近更新 更多