3
如果我写邮件给封闭管道,然后我的程序崩溃如何在写入之前检查管道是否打开?
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连接到读数结束为 已关闭的管道或插座。发生这种情况时,写入过程也会收到一个SIGIPIPE信号。
所以在这之前的测试工作还需要忽略SIGPIPE
:
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
perror("signal");