Reputation: 1010
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?
Upvotes: 2
Views: 2831
Reputation: 321
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.
Upvotes: 4
Reputation: 13374
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;
}
Upvotes: 3