当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - break from infinite loop from console

问题描述:

I have a console server which listens clients and does what they need. But sometimes I need end server and I don't know how I can do it properly. Because I can hit ctrl+c to end program, but I have important code after loop which I need to do.

main_function(){

while(true){

listen();

}

do_something_important();

}

Can I catch some signal from console and run function to do important stuff and properly end?

end_program(){

do_something_important();

return 0;

}

Or what is the best way what I can do in my situation?

网友答案:

You could use signals:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

static void on_close(int signal)
{
    puts("Cleaning up...");
    exit(EXIT_SUCCESS);
}

int main(void)
{
    signal(SIGINT, on_close);

    while (1)
    {
    }

    return EXIT_SUCCESS;
}
网友答案:

Use signals like Pragmateek described, but make sure to only set a flag in your signal handler (like exitnow = true), and check for this flag in your main loop. Signals may interrupt your main program at any point in your code, so if you want to be sure that your logic is not going to be randomly interrupted or cut short, use signal handlers just to set flags.

分享给朋友:
您可能感兴趣的文章:
随机阅读: