如果你不做fclose()就退出程序会怎么样? [英] What happens if you exit a program without doing fclose()?

查看:554
本文介绍了如果你不做fclose()就退出程序会怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:



如果我退出程序而没有关闭文件,会发生什么?

(例如,一些操作系统级别的文件描述符数组没有被释放..?)

而在这两种情况下的答案相同




  • 已编程退出

  • 意外崩溃


    代码示例



    使用程序退出的意思是这样的:

      int main(){
    fopen(foo.txt,r);
    exit(1);





    $ b

    意外崩溃的意思是这样的:

      int main(){
    int * ptr = NULL;
    fopen(foo.txt,r);
    ptr [0] = 0; //导致分段错误发生



    $ h $ PS $ h

    如果答案是依赖于编程语言,那么我想知道关于C和C ++的问题。

    如果答案依赖于操作系统,那么我很感兴趣在Linux和Windows的行为。

    解决方案

    这取决于你如何退出。在受控制的情况下(通过 exit() 或从 main())返回时,(输出)缓冲区中的数据将被刷新并且文件按顺序关闭。如果你的程序崩溃失控,或者如果它调用其中一个替代方法 /pubs.opengroup.org/onlinepubs/9699919799/functions/_Exit.htmlrel =noreferrer> _exit() _Exit() 函数,那么系统仍然会清理(关闭)打开的文件描述符并释放其他资源,但是缓冲区不会被刷新等。


    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.

    解决方案

    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.

    这篇关于如果你不做fclose()就退出程序会怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆