关闭/清理"混合"文件描述符/套接字
时间:2020-03-06 14:28:59 来源:igfitidea点击:
当我使用accept()创建套接字并使用fdopen()从中创建文件时,我该怎么做以清理所有内容?我是否需要在FILE上执行fclose(),在套接字上执行shutdown()和close(),还是只需要执行shutdown()和/或者close()或者fclose()?如果不执行fclose(),是否必须手动释放FILE指针?
解决方案
这里有两件事需要清理:由" FILE"表示的流和由套接字表示的文件描述符。我们需要先关闭流,然后关闭文件描述符。因此,一般来说,我们将需要先对所有文件对象执行fclose(),然后对任何文件描述符执行close()。
就个人而言,当我想自己清理时,我从未使用过shutdown()
,所以我不能说。
编辑
其他人正确地指出,fdclose()
也将关闭底层文件描述符,并且由于在关闭文件描述符上调用close()
会导致错误,因此在这种情况下,我们仅需要fdclose()
。
来自man fdopen:
The file descriptor is not dup’ed, and will be closed when the stream created by fdopen() is closed
因此,我只使用fclose(),它也会关闭基础文件描述符。我也不知道是否需要shutdown()。
从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.
如果将套接字包装在流中,则对shutdown()可能不再有意义,至少在没有先刷新流的情况下才有意义。但是我不会发誓,因为我不知道我们想要shutdown()而不是close()没有用处。