What's a good manner to use SIGINT for killing app in C++?

143 views Asked by At

I'm developing a server application and want to use SIGINT for killing application. Although I know 2 ways, I'm not sure which are good way to kill this application.

Are there any better ways to handle SIGING?

int main() {
 startServer();

 1. while(true) {sleep(3); if(sigFlag) break;}
 2. std::getline(std::cin, param);

 stopServer();
 return 0;
}
2

There are 2 answers

3
HM Manya On
#include<stdio.h>
#include<signal.h>
#include<unistd.h>

bool run = true;

void sig_handler(int signo)
{
  if (signo == SIGINT)
  {
    printf("received SIGINT\n");
    run = false;
  }
}

int main(void)
{
  if (signal(SIGINT, sig_handler) == SIG_ERR)
  printf("\ncan't catch SIGINT\n");
  // A long long wait so that we can easily issue a signal to this process
  while(run) 
    sleep(1);
  return 0;
}

Source: http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/

Instead of printf use return or exit

0
Charlie On

The first method is better. Server application should run background and can not process the input and output from termination.

Another key point is the second method will block the server. The signal method way will avoid this problem.