探讨一下pause函数的用法: 1 #include<stdio.h> 2 #include<signal.h> 3 #include<unistd.h> 4 void signhand(int signo) 5 { 6 int i; 7 for(i=0;i<10;i++) 8 { 9 printf("signhand number is %d\n",i); 10 sleep(1); 11 } 12 } 13 int main() 14 { 15 int i; 16 signal(SIGALRM,signhand); 17 alarm(3); 18 pause(); //进程挂起 19 for(i=0;i<10;i++) 20 { 21 printf("main number is %d\n",i); 22 sleep(1); 23 } 24 return 0; 25 }
程序运行结果:(其实程序是执行到pause后等待信号的触发,信号触发后,执行信号函数,执行信号函数完毕后,返回主函数继续执行!)
signhand number is 0 signhand number is 1 signhand number is 2 signhand number is 3 signhand number is 4 signhand number is 5 signhand number is 6 signhand number is 7 signhand number is 8 signhand number is 9 main number is 0 main number is 1 main number is 2 main number is 3 main number is 4 main number is 5 main number is 6 main number is 7 main number is 8 main number is 9
再看一个牛X的程序:我们设置在10s后,进程向自身发送SIGALRM信号
1 #include<stdio.h> 2 #include<signal.h> 3 #include<unistd.h> 4 void signhand(int signo) 5 { 6 int i; 7 for(i=0;i<5;i++) 8 { 9 printf("signhand number is %d\n",i); 10 sleep(1); 11 } 12 } 13 int main() 14 { 15 int i; 16 signal(SIGALRM,signhand); 17 alarm(10); 18 for(i=0;i<5;i++) 19 { 20 printf("main number is %d\n",i); 21 sleep(1); 22 } 23 return 0; 24 }
该程序的运行结果如下:
1 main number is 0 2 main number is 1 3 main number is 2 4 main number is 3 5 main number is 4
可以看到该函数没有触发信号函数的,在主函数运行过程中根本没有信号的相关操作!
时间: 2024-11-05 12:54:27