#include <stdio.h> #include <unistd.h> #include <signal.h> void catch_int(int sig_num){ signal(SIGINT,catch_int);//再次设置信号回调函数。ctrl+c:INT信号,ctrl+Z:挂起,TSTP信号.ctrl+\:发送BRT信号,进程立即中止,类似于ctrl-c,但灵活性更强 printf("ctrl+c press!\n"); //ctrl+c失去作用,在此仅打印 fflush(stdout); } //深未来技术 http://deepfuture.javaeye.com void catch_alarm(int sig_num){ printf("timeout,bye!\n"); alarm(0);//清除定时器 exit(0); } int main(void){ int x; signal(SIGALRM,catch_alarm); //定时器信号 signal(SIGINT,catch_int); //设置ctrl-c信号的回调函数是catch_int,以拦截ctrl-c。 printf("please input an integer:"); fflush(stdout); alarm(20);//20秒时限 scanf("%d",&x);//20秒内用户输入一个数 printf("integer is :%d\n",x); return 0; }
?knoppix@Microknoppix:/mnt-system/deepfuture$ gcc -o test9 test9.c
test9.c: In function 'catch_alarm':
test9.c:14: warning: incompatible implicit declaration of built-in function 'exit'
knoppix@Microknoppix:/mnt-system/deepfuture$ ./test9
please input an integer:^Cctrl+c press!
^Cctrl+c press!
^Cctrl+c press!
^Cctrl+c press!
timeout,bye!