- 论坛徽章:
- 0
|
假设自己写一个服务程序,开机后自动运行,是一个后台服务程序。
如果其它用户通过其它命令(比如root用户输入reboot命令)或其它程序要关闭计算机,我的程序会收到SIGTERM信号,但捕捉不到SIGKILL信号,收到SIGTERM信号后如何开始保存自己的数据到磁盘上呢?
我的测试代码如下:
- /************然后我来专门处理关机时收到的信号15**********************/
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- void sighandler(int);
- int main(int argc, char ** argv)
- {
- int x = 0;
- signal(SIGTERM, sighandler);
- signal(SIGQUIT, sighandler);
- while(1) {
- /*printf("now %d\n", x++);*/
- usleep(100);
- }
- }
- void sighandler(int sig)
- {
- FILE * fp;
- int x = 0;
- fp = fopen("haltsignal.txt", "a+");
- if(!fp) return;
- fprintf(fp, "signal.%d received, now begin to save data:\n", sig);
- for(x = 1; x <= 5; x++) {fprintf(fp, "save data.%d\n", x); fflush(fp);}
- fclose(fp);
- }
复制代码
当这个程序运行起来,在另一个终端输入reboot命令,然后再看haltsignal.txt却没有内容。 |
|