我编译了程序。启动它并等待。我打开另一个终端,并使用命令“kill pid”或“kill -15 pid”或“kill -SIGTERM pid”杀死任何正在运行的程序(将 PID 替换为实际的进程 ID)。被杀死的程序退出,但无法捕获 SIGTERM 以打印“完成”。
我在这里复制代码:https ://airtower.wordpress.com/2010/06/16/catch-sigterm-exit-gracefully/ 。
我可以帮你吗?我很感激所有的答案。
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
volatile sig_atomic_t done = 0;
void term(int signum)
{
done = 1;
}
int main(int argc, char *argv[])
{
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = term;
sigaction(SIGTERM, &action, NULL);
int loop = 0;
while (!done)
{
int t = sleep(3);
/* sleep returns the number of seconds left if
* interrupted */
while (t > 0)
{
printf("Loop run was interrupted with %d "
"sec to go, finishing...\n", t);
t = sleep(t);
}
printf("Finished loop run %d.\n", loop++);
}
printf("done.\n");
return 0;
}