我可以在C语言中对一个文件描述符调用两次shutdown吗?
我正在使用 c 。 我有 fd1 作为文件描述符,我可以像这样调用两次吗?
main () {
....
shutdown(fd1, SHUT_WR);
....
shutdown(fd1, SHUT_WR);
....
}
我个人认为它是有效的,因为 fd1 还没有真正免费。只是想找个人确认一下
I am using c .
I have fd1 as a file descriptor, can I call like this twice?
main () {
....
shutdown(fd1, SHUT_WR);
....
shutdown(fd1, SHUT_WR);
....
}
I personally think it works because fd1 has not been really free yet. Just want somebody to confirm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该检查第二次调用的返回值 -
shutdown(2)
可能返回-1
- 并检查errno(3)
。You should check the return value of the second call -
shutdown(2)
probably returns-1
- and check the value oferrno(3)
.在我的 Linux 和 glibc 版本上,我可以在同一个打开的套接字上多次调用
shutdown
。它会很高兴地返回 0,直到套接字实际上在该方向上被拆除,然后将返回 -1,并带有 errno == ENOTCONN。它不会返回EBADF
,直到您关闭
FD,然后您无论如何都不应该继续使用该FD。这一事实实际上非常有用,因为您可以在循环中调用 shutdown 来检测连接是否已以某种方式断开。对套接字上的错误进行
epoll
似乎可以在正确的时间将其唤醒。On my version of Linux and glibc, I can call
shutdown
multiple times on the same open socket. It will happily return 0 until the socket is actually torn down in that direction and will then return -1 witherrno == ENOTCONN
. It will not returnEBADF
until youclose
the FD and then you shouldn't still be using that FD anyway.This fact is actually pretty useful, since you can call shutdown in a loop in order to detect that the connection has been torn down one way or another.
epoll
ing for errors on the socket appears to wake it up at the right time.调用
shutdown
只是启动 TCP 级别的关闭序列。除非您对其调用close
,否则套接字描述符永远不会被释放以供重用。您可以根据需要多次调用
shutdown
,但后续调用可能会导致错误。当您使用完套接字后,调用
close
。Calling
shutdown
simply initiates a TCP level shutdown sequence. The socket descriptor is never released for reuse until you callclose
on it.You can call
shutdown
as often as you like, though it's likely that subsequent calls will result in an error.Call
close
when you are done with the socket.您可以调用它一次来关闭输出,然后再次调用它来关闭输入,反之亦然。调用它两次来关闭输出肯定不会发送两个 FIN,无论它会做什么。调用它两次来关闭输入也不能做任何事情两次。所以这些都不可能有任何实际意义。
注意:您根本无法在文件描述符上调用它。您可以在套接字描述符上调用它。
You can call it once to shutdown the output and again to shutdown the input, or vice versa. Calling it twice to shutdown the output certainly won't send two FINs, whatever else it may do. Calling it twice to shutdown the input can't do anything twice either. So neither of those can possibly have any actual point.
NB You can't call it on a file descriptor at all. You can call it on a socket descriptor.