c++ - 在 C++ 中使用 SIGINT 杀死应用程序的好方法是什么?

标签 c++ sigint

我正在开发服务器应用程序并想使用 SIGINT 来终止应用程序。虽然我知道 2 种方法,但我不确定哪种方法适合终止此应用程序。

有没有更好的方法来处理 SIGING?

int main() {
 startServer();

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

 stopServer();
 return 0;
}

最佳答案

#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;
}

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

使用 return 或 exit 代替 printf

关于c++ - 在 C++ 中使用 SIGINT 杀死应用程序的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931884/

相关文章:

python - 使用 ^C/KeyboardInterrupt 在子线程中中断 Python raw_input()

c - 如何清理 SIGINT 处理程序中的本地数据

c++ - 如何重载其参数仅因 gcc vector 扩展 vector_size 属性不同而不同的函数?

c++ - D3D11CreateDevice() 返回垃圾值并失败

python - Node.js:无法处理从 process.kill() 发送的 SIGINT

c - 面向 C/C++ 开发人员的 Eclipse 和 Ctrl+C

c++ - Libpqxx 连接池

c++ - 奇怪的 C++ 模板问题

c++ - 有没有办法强制用户显式指定模板参数类型?

python - 捕获 SIGINT 并调用对象中的方法