Should we use exit() in C?

前端 未结 7 1154
醉梦人生
醉梦人生 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 17:08

    Depending on what you are doing, exit may be the most logical way out of a program in C. I know it's very useful for checking to make sure chains of callbacks work correctly. Take this example callback I used recently:

    unsigned char cbShowDataThenExit( unsigned char *data, unsigned short dataSz,unsigned char status)
    {
    
        printf("cbShowDataThenExit with status %X (dataSz %d)\n", status, dataSz);
        printf("status:%d\n",status);
        printArray(data,dataSz);
        cleanUp();
        exit(0);
    }
    

    In the main loop, I set everything up for this system and then wait in a while(1) loop. It is possible to make a global flag to exit the while loop instead, but this is simple and does what it needs to do. If you are dealing with any open buffers like files and devices you should clean them up before close for consistency.

提交回复
热议问题