简体   繁体   English

EPIPE之后关闭套接字文件描述符

[英]Closing socket file descriptor after EPIPE

After ignoring SIGPIPE with a call to signal(), there is a possibility that a write() call will fail with errno set equal to EPIPE. 通过调用signal()忽略SIGPIPE之后,如果errno设置为EPIPE,则write()调用可能会失败。 Do I still have to close the file descriptor like in the example below? 是否仍然需要像下面的示例一样关闭文件描述符?

if (write(sock_fd, buf, len) < 0) {
    if (errno == EPIPE) {
        close(sock_fd);
    }
}

Remember that when you create a pipe, using the system call of the same name, you get two file descriptors: one for reading and one for writing. 请记住,当使用相同名称的系统调用创建管道时,将获得两个文件描述符:一个用于读取,一个用于写入。 You get EPIPE from a write operation, on the write fd, when the read fd has been closed. 关闭读取 fd时,可以通过对写入fd的写入操作获得EPIPE。 The write fd is still open. 写入fd仍处于打开状态。 If you try to write to it again, you'll get EPIPE again. 如果您尝试再次写入,则会再次获得EPIPE。

(Often, when this happens, the pipe was set up by a shell or some other parent process, and the read fd was never available to your program, but that doesn't matter to the kernel. It was open in some process(es) and now it isn't.) (通常,发生这种情况时,管道是由Shell或其他父进程建立的,并且读取的fd永远不会对您的程序可用,但对内核无关紧要。它在某些进程中是打开的),现在不是。)

Since it's still open, you do need to close it. 由于它仍处于打开状态,因此您需要将其关闭。 However, exiting automatically closes all fds that are still open. 但是,自动退出将关闭所有仍打开的fds。 So if the very next thing you'd do after closing the pipe is to exit, then you don't need to bother closing it first. 因此,如果您在关闭管道之后要做的下一件事是退出,那么您就不必先费心关闭它。 Since it is a pipe, and you already got EPIPE, there can't be any delayed write errors that close might report. 由于这是一个管道,你已经得到了EPIPE,不能有任何延迟写入错误的close可能会报告。

You always have to close file descriptors. 您始终必须关闭文件描述符。 No ifs, no buts. 没有,没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM