【发布时间】: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是否仍然打开?
【问题讨论】:
如果我将消息写入封闭管道,那么我的程序会崩溃
if (write(pipe, msg, strlen(msg)) == -1) {
printf("Error occured when trying to write to the pipe\n");
}
在我写信之前如何检查pipe是否仍然打开?
【问题讨论】:
正确的方法是测试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");
【讨论】: