windows下面可以主线程while loop接受input;但是觉得很丑。
linux没办法这样,可以用注册信号的办法。实现起来也不难:
#include "stdio.h"
#include "unistd.h"
#include "signal.h"
#include "error.h"
volatile bool isStop = false;
static void handle_sig(int signum)
{
if (SIGUSR1 == signum) {
isStop = true;
printf("get sig %d and stop app\n", signum);
}
}
int main()
{
struct sigaction sga;
sga.sa_flags = 0;
sga.sa_handler = handle_sig;
sigaction(SIGUSR1, &sga, NULL);
while (true) {
if (isStop)
break;
}
printf("do some clean work here!\n");
}
后台运行,然后干掉它的时候发送kill -USR1 进程ID就行了。