0

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;
}
jef
  • 3,890
  • 10
  • 42
  • 76

2 Answers2

1
#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

Damon
  • 67,688
  • 20
  • 135
  • 185
HM Manya
  • 83
  • 1
  • 8
  • How does that answer the question? He wants to kill a process, not handle kill attempts.... – wallyk Jun 19 '15 at 07:07
  • @wallyk, can you clarify where the OP states they want to kill an external process? As I (and probably this answer) read the question, they want to know a good way to handle the `SIGINT` signal within a C++ application (not handle a `SIGINT` for a separate process) .. ?? – txtechhelp Jun 19 '15 at 07:14
  • 1
    It's also worth noting if the OP is using Windows, the C `signal` facility is only half the equation; WINAPI has `SetConsoleCtrlHandler` which handles the `CTRL+C` events (POSIX systems that use `signal` will catch the `SIGINT` signal on a `CTRL+C` event, Windows needs to set the `SetConsolCtrlHandler`). – txtechhelp Jun 19 '15 at 07:28
0

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.

Charlie
  • 418
  • 3
  • 9