题目3:
编写一个程序实现倒计时退出功能,当进程收到SIGUSR1信号时开始倒计时,3秒钟后退出程序。
要求在终端上输出收到信号并开始倒计时的过程
如:
The process is terminating in 3 sec...
The process is terminating in 2 sec...
The process is terminating in 1 sec...
1 #include <sys/types.h> 2 #include <unistd.h> 3 #include <signal.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <stdio.h> 7 #include <errno.h> 8 #include <signal.h> 9 10 int g_tag; 11 12 void myhandle(int num) 13 { 14 printf("recv signal id num : %d \n", num); 15 if (num == 10) 16 { 17 g_tag = 0; 18 } 19 } 20 21 int main(void) 22 { 23 24 g_tag = 1; 25 26 27 if ( signal(SIGUSR1, myhandle) == SIG_ERR ) 28 { 29 perror("signal err"); 30 return 0; 31 } 32 33 while(1) 34 { 35 if(g_tag == 0) 36 { 37 printf("The process is terminating in 3 sec...\n"); 38 sleep(1); 39 printf("The process is terminating in 2 sec...\n"); 40 sleep(1); 41 printf("The process is terminating in 1 sec...\n"); 42 sleep(1); 43 break; 44 } 45 } 46 47 48 return 0; 49 }
时间: 2024-10-10 23:26:29