如果退出程序而不执行 fclose() 会发生什么?
问题:
如果我退出程序而不关闭文件会发生什么?
是否发生了一些不好的事情(例如,某些操作系统级别的文件描述符数组未释放..?)
两种情况下答案相同
- 并且在编程退出
- 意外崩溃的
代码示例:
随着编程退出我的意思是这样的:
int main(){
fopen("foo.txt","r");
exit(1);
}
随着意外崩溃我的意思是这样的:
int main(){
int * ptr=NULL;
fopen("foo.txt","r");
ptr[0]=0; // causes segmentation fault to occur
}
PS
如果答案取决于编程语言,那么我想了解 C 和 C++。
如果答案取决于操作系统,那么我对 Linux 和 Windows 行为感兴趣。
Question:
What happens if I exit program without closing files?
Are there some bad things happening (e.g. some OS level file descriptor array is not freed up..?)
And to the answer the same in both cases
- programmed exiting
- unexpected crash
Code examples:
With programmed exiting I mean something like this:
int main(){
fopen("foo.txt","r");
exit(1);
}
With unexpected crash I mean something like this:
int main(){
int * ptr=NULL;
fopen("foo.txt","r");
ptr[0]=0; // causes segmentation fault to occur
}
P.S.
If the answer is programming language dependent then I would like to know about C and C++.
If the answer is OS dependent then I am interested in Linux and Windows behaviour.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这取决于你如何退出。在受控情况下(通过
exit()
或从main()
返回),(输出)缓冲区中的数据将被刷新并按顺序关闭文件。该进程拥有的其他资源也将被释放。如果您的程序崩溃失控,或者它调用了替代方法之一
_exit()
或_Exit()
函数,那么系统仍然会清理(关闭)打开的文件描述符并释放其他资源,但缓冲区不会被冲走等等。It depends on how you exit. Under controlled circumstances (via
exit()
or a return frommain()
), the data in the (output) buffers will be flushed and the files closed in an orderly manner. Other resources that the process had will also be released.If your program crashes out of control, or if it calls one of the alternative
_exit()
or_Exit()
functions, then the system will still clean up (close) open file descriptors and release other resources, but the buffers won't be flushed, etc.操作系统会帮你整理。这就像去见朋友一样——关上浴室的门而不是让他们帮你做是有礼貌的。
The OS tidies up for you. It is like going around to a friends - it is polite to shut the bathroom door and not have them do it for you.
属于您进程的所有句柄都将被清理。然而,任何“命名”内核对象(例如命名管道和其他对象)都会保留下来。
All handles that belong to your process will be cleaned up. However any "named" kernel objects like named pipes and others will stick around.