如果 fclose() 失败,文件描述符是否仍然打开?
If fclose() fails, is the file descriptor still open?
将以下代码 运行 想象成一个线程:
void *thread_worker(void *q) {
for (;;) {
int fd = some_queue_get(q);
FILE *writer = fdopen(fd, "w");
if (!writer) { perror("fdopen"; close(fd); continue; }
// do something with writer
if (fclose(writer) == EOF) {
perror("fclose writer");
// should fd be closed here?
close(fd);
}
}
fclose(3)
可能因各种原因而失败 - 是否可以保证 that/when 底层文件描述符已关闭或之后仍处于打开状态?
- 如果在刷新失败时 fd 没有被 fclose 关闭,则在没有额外关闭的情况下泄漏 fds。
- 如果 fd 被 fclose 关闭,额外的关闭可能会关闭由其他线程新打开的文件描述符。
man fclose
也没有在我的系统上提供答案,但是 man 3p fclose
揭示了 official version from the POSIX Programmer's manual,这在这个问题上更加全面:
The fclose()
function shall perform the equivalent of a close()
on the file descriptor that is associated with the stream pointed to by stream.
答案是否,C标准对此不明确(强调我的):
7.21.5.1 The fclose
function
Synopsis
#include <stdio.h>
int fclose(FILE *stream);
Description
A successful call to the fclose
function causes the stream pointed to by stream
to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by the setbuf
or setvbuf
function is disassociated from the stream (and deallocated if it was automatically allocated).
Returns
The fclose
function returns zero if the stream was successfully closed, or EOF
if any errors were detected.
将以下代码 运行 想象成一个线程:
void *thread_worker(void *q) {
for (;;) {
int fd = some_queue_get(q);
FILE *writer = fdopen(fd, "w");
if (!writer) { perror("fdopen"; close(fd); continue; }
// do something with writer
if (fclose(writer) == EOF) {
perror("fclose writer");
// should fd be closed here?
close(fd);
}
}
fclose(3)
可能因各种原因而失败 - 是否可以保证 that/when 底层文件描述符已关闭或之后仍处于打开状态?
- 如果在刷新失败时 fd 没有被 fclose 关闭,则在没有额外关闭的情况下泄漏 fds。
- 如果 fd 被 fclose 关闭,额外的关闭可能会关闭由其他线程新打开的文件描述符。
man fclose
也没有在我的系统上提供答案,但是 man 3p fclose
揭示了 official version from the POSIX Programmer's manual,这在这个问题上更加全面:
The
fclose()
function shall perform the equivalent of aclose()
on the file descriptor that is associated with the stream pointed to by stream.
答案是否,C标准对此不明确(强调我的):
7.21.5.1 The
fclose
functionSynopsis
#include <stdio.h> int fclose(FILE *stream);
Description
A successful call to thefclose
function causes the stream pointed to bystream
to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by thesetbuf
orsetvbuf
function is disassociated from the stream (and deallocated if it was automatically allocated).Returns
Thefclose
function returns zero if the stream was successfully closed, orEOF
if any errors were detected.