2

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?

Marek Čačko
  • 980
  • 2
  • 21
  • 31
  • possible duplicate of [What happens when you close a c++ console application](http://stackoverflow.com/questions/696117/what-happens-when-you-close-a-c-console-application) – GSerg Jun 23 '13 at 14:11
  • possible duplicate of [How to handle a ctrl-break signal in a command line interface](http://stackoverflow.com/q/181413/11683) – GSerg Jun 23 '13 at 14:12

2 Answers2

4

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.

nikkiauburger
  • 321
  • 2
  • 4
  • 1
    +1 for the best practice You can even add a counter if the main loop is stuck so that if the user requests to end say 3 times you exit directly. – Pragmateek Jun 23 '13 at 14:45
3

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;
}
Pragmateek
  • 13,174
  • 9
  • 74
  • 108