在尝试写入之前检查管道是否损坏?

Laz*_*ear 5 c linux posix pipe sigpipe

是否有可能在尝试写入/读取之前检查管道是否损坏,所以我可以跳过它并继续该程序?

我正在利用while循环写入从父节点到多个子节点的管道.在循环过程中,几个孩子将关闭.当循环到来并尝试再次写入它们时,我的程序关闭,因为它被管道破坏后被SIGPIPE杀死.我知道管子坏了,我给孩子们编程关闭他们的管道并退出(必要).我仍然希望完成循环并继续使用该程序.我想检查管道是否损坏,如果损坏则跳过它(没有错误输出),继续执行程序(其他子代仍然需要写入).

那么,有可能吗?c中的一个例子很棒.

这是我要问的简单的伪代码表示:

int i = 0;

while(i != 5)
{
    if (mypipe[WRITE] is BROKEN)
        //Do Nothing ---Basically Skip

    else if (some condition)
        write(mypipe[WRITE]);

    i++;
}
Run Code Online (Sandbox Code Playgroud)

这个问题与我之前的帖子有关,尽管我的问题背景不同.您可以在那里查看实际程序的代码.

nos*_*nos 5

我的程序因为被SIGPIPE杀死而关闭

如果安装忽略SIGPIPE的信号处理程序,则可以更改该行为,这样对管道的write()调用将返回错误而不是终止程序:

  signal(SIGPIPE, SIG_IGN);
Run Code Online (Sandbox Code Playgroud)

然后你简单检查一下

ssize_t rc;
rc = write(...);
if (rc == -1) {
    if (errno == EPIPE) {
         //it's broken
    }
 //some other error occured.
}
Run Code Online (Sandbox Code Playgroud)


use*_*342 5

您可以设置一个信号处理程序来忽略SIGPIPE,然后写入缓冲区并检查错误代码:

/* initialization */
signal(SIGPIPE, SIG_IGN);
...

/* try writing to pipe and detect broken pipe */
ssize_t written = write(mypipe[WRITE], buf, size);
if (written == -1 && errno == EPIPE)
  ... remove pipe from the list and continue processing
Run Code Online (Sandbox Code Playgroud)