关闭/清理“混合”内容 文件描述符/套接字

发布于 2024-07-05 07:35:35 字数 195 浏览 12 评论 0原文

当我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁月无声 2024-07-12 07:35:35

来自 man fdopen:

文件描述符不会重复,并且会在 fdopen() 创建的流关闭时关闭

所以我只使用 fclose(),它也会关闭底层文件描述符。 我也不知道是否需要 shutdown() 。

From man fdopen:

The file descriptor is not dup’ed, and will be closed when the stream created by fdopen() is closed

So I would just use fclose(), which also closes the underlying file descriptor. I don't know whether shutdown() is needed, either.

雨巷深深 2024-07-12 07:35:35

来自 http://opengroup.org/onlinepubs/007908775/xsh/fclose.html

fclose() 函数将执行
close() 在文件描述符上
与指向的流关联
通过流。

如果您将套接字包装在流中,那么 shutdown() 可能不再有意义,至少在不先刷新流的情况下是这样。 但我不会发誓这一点,因为我不知道除了 close() 之外,还有什么地方需要 shutdown() 。

From http://opengroup.org/onlinepubs/007908775/xsh/fclose.html

The fclose() function will perform a
close() on the file descriptor that is
associated with the stream pointed to
by stream.

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().

逐鹿 2024-07-12 07:35:35

这里有两件事需要清理:由 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 to fclose() any FILE objects, then close() 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 calling close() on a close file descriptor will lead to an error, in this case you only need fdclose().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文