fclose(stdout)关闭的到底是C标准库的流,还是系统的fd?

gakujubei 2015-01-25 12:15:44
之前我对于标准I / O的理解是,在系统输入输出fd的基础上,做一个C语言运行时库的包装,因此fclose(stdout)应该是关闭了stdout这个"流",而系统的STDOUT_FILENO应该没有被关闭。
但是我测试了一下,如下:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
size_t w = fwrite("hw\n", 3, 1, stdout);
fclose(stdout);
write(STDOUT_FILENO, "again\n", 3);
return 0;
}

结果是只打印了hw一次,并没有打印again。这是为什么呢,和我的预期有点不一致啊。fclose(stdout)不仅仅是在C运行时库这一层起了作用,看起来还影响了系统的底层行为。这样的话,C运行时库的I/O流就不仅仅是一个包装了,它本身的状态也影响了系统API的调用?
求解释!
...全文
202 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
mymtom 2015-01-26
  • 打赏
  • 举报
回复
关闭 FILE, 同时关闭fd int fclose(FILE *stream); DESCRIPTION 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 is written to the file; any unread buffered data is discarded. The stream is disassociated from the file. If the associated buffer was automatically allocated, it is deallocated. It marks for update the st_ctime and st_mtime fields of the underlying file, if the stream was writable, and if buffered data had not been written to the file yet. The fclose() function will perform a close() on the file descriptor that is associated with the stream pointed to by stream. After the call to fclose(), any use of stream causes undefined behaviour.
heshiqibu 2015-01-25
  • 打赏
  • 举报
回复
流应该关联到了文件吧,关闭流的时候应该把进程所对应的文件表中的打开文件关闭了,这样进程没有持有该文件了,再向流里写东西也就没用了
gakujubei 2015-01-25
  • 打赏
  • 举报
回复
引用 1 楼 zhxianbin 的回复:
stdout 是同一个啊
我的意思是,我期待fclose关闭的是文件流,而不是fd本身啊
zhxianbin 2015-01-25
  • 打赏
  • 举报
回复
stdout 是同一个啊

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧