Should we use exit() in C?

前端 未结 7 1142
醉梦人生
醉梦人生 2020-12-02 16:44

There is question about using exit in C++. The answer discusses that it is not good idea mainly because of RAII, e.g., if exit is called somewhere

7条回答
  •  抹茶落季
    2020-12-02 16:53

    Yes, it is ok to use exit in C.

    To ensure all buffers and graceful orderly shutdown, it would be recommended to use this function atexit, more information on this here

    An example code would be like this:

    void cleanup(void){
       /* example of closing file pointer and free up memory */
       if (fp) fclose(fp);
       if (ptr) free(ptr);
    }
    
    int main(int argc, char **argv){
       /* ... */
       atexit(cleanup);
       /* ... */
       return 0;
    }
    

    Now, whenever exit is called, the function cleanup will get executed, which can house graceful shutdown, clean up of buffers, memory etc.

提交回复
热议问题