What happens if you exit a program without doing fclose()?

放肆的年华 提交于 2020-01-03 07:29:48

问题


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.


回答1:


It depends on how you exit. Under controlled circumstances (via exit() or a return from main()), 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.




回答2:


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.




回答3:


All handles that belong to your process will be cleaned up. However any "named" kernel objects like named pipes and others will stick around.



来源:https://stackoverflow.com/questions/7370363/what-happens-if-you-exit-a-program-without-doing-fclose

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!