先看代码:例1,alarm()
#include <unistd.h> #include <signal.h> #include <stdio.h> #include <errno.h> void alarm_handler(int sig) { printf("hello!--sig:%d\n",sig); alarm(1); } int main() { if (signal(SIGALRM, alarm_handler) == SIG_ERR) { //安装信号,SIGALRM的编号为14 perror("signal"); return 0; } alarm(1); while(1) { //让进程一直存在 pause(); } return 0; }
结果:
[lgh@localhost test]$ ./a.out
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
---------------------------------------------
它会每秒打印一行"hello!--sig:14".
应用:使进程定期性地做某些操作.例如,给低速的IO操作给个时间上限,定期查看进程是否存在,连接是否中断等.
例2:setitimer(),这个比alarm()强大,可以有3种模式进行计数.
#include <unistd.h> #include <signal.h> #include <stdio.h> #include <errno.h> #include <sys/time.h> void alarm_handler(int sig) { printf("hello!--sig:%d\n",sig); } int main() { struct itimerval t; /* 第一次执行前的时间间隔*/ t.it_value.tv_usec = 0; t.it_value.tv_sec = 3; /* 以后每间再次执行的时间间隔*/ t.it_interval.tv_usec = 0; t.it_interval.tv_sec = 1; if( setitimer(ITIMER_REAL, &t, NULL) < 0 ){ perror("settimer"); return -1; } if (signal( SIGALRM, alarm_handler) == SIG_ERR) { perror("signal"); return -1; } while(1){ pause(); } return 0; } /* int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue); int which: ITIMER_REAL : 以系统真实的时间来计算,时间到发送SIGALRM信号。 ITIMER_VIRTUAL :以该进程在用户态下花费的时间来计算,时间到发送SIGVTALRM信号。 ITIMER_PROF : 以该进程在用户态下和内核态下所费的时间之和来计算,时间到发送SIGPROF信号。 struct itimerval { struct timerval it_interval; //执行第一次后,以后每次计数的间隔 struct timerval it_value; //第一次计数的时间间隔 }; struct timeval { long tv_sec; long tv_usec; } */
结果:
[lgh@localhost test]$ ./a.out
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
---------------------------------------
启动程序后,隔3秒打印第一行,接下来每1秒打印一行.