关闭/清理“混合”内容 文件描述符/套接字
当我使用accept()创建一个套接字并使用fdopen()从中创建一个文件时,我需要做什么来清理所有内容? 我是否需要对 FILE 执行 fclose(),对套接字执行 shutdown() 和 close(),还是只需要 shutdown() 和/或 close() 或 fclose()? 如果我不执行 fclose(),是否必须手动 free() FILE 指针?
When I create a socket using accept() and make a FILE out of it using fdopen(), what do I have to do to clean everything up? Do I need to do fclose() on the FILE, shutdown() and close() on the socket, or only the shutdown() and or close() or fclose()? If I don't do fclose(), do I have to free() the FILE pointer manually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 man fdopen:
所以我只使用 fclose(),它也会关闭底层文件描述符。 我也不知道是否需要 shutdown() 。
From man fdopen:
So I would just use fclose(), which also closes the underlying file descriptor. I don't know whether shutdown() is needed, either.
来自 http://opengroup.org/onlinepubs/007908775/xsh/fclose.html
如果您将套接字包装在流中,那么 shutdown() 可能不再有意义,至少在不先刷新流的情况下是这样。 但我不会发誓这一点,因为我不知道除了 close() 之外,还有什么地方需要 shutdown() 。
From http://opengroup.org/onlinepubs/007908775/xsh/fclose.html
If you've wrapped your socket in a stream it probably no longer makes sense to shutdown(), at least not without flushing the stream first. But I won't swear to that, because I don't know that there are no uses where you'd want to shutdown() rather than just close().
这里有两件事需要清理:由
FILE
表示的流和由套接字表示的文件描述符。 您需要先关闭流,然后关闭文件描述符。 因此,一般来说,您需要fclose()
任何FILE
对象,然后close()
任何文件描述符。就我个人而言,当我想自己清理时,我从未使用过 shutdown(),所以我不能说。
编辑
其他人正确地指出,
fdclose()
也会关闭底层文件描述符,并且由于在关闭文件描述符上调用close()
将导致错误,在在这种情况下,您只需要fdclose()
。You have 2 things here you need to clean up: the stream represented by
FILE
and the file descriptor represented by the socket. You need to close the stream first, then the file descriptor. So, in general you will need tofclose()
anyFILE
objects, thenclose()
any file descriptors.Personally I have never used
shutdown()
when I want to cleanup after myself, so I can't say.edit
Others have correctly pointed out that
fdclose()
will also close the underlying file descriptor, and since callingclose()
on a close file descriptor will lead to an error, in this case you only needfdclose()
.