信号的学习.
例1: 终端窗口变化产生信号SIGWINCH
mysignal.c
#include#include #include #include #include #include #include #include void handler(int signum){ puts("windows!!!");}int main(int argc, char *argv[]){ signal(SIGWINCH,handler); getchar(); return 0;}
编译链接运行, 用鼠标拖动终端边框, 输出结果如下:
回车退出.
例2: fork()创建子进程(状态改变)时, 产生的信号SIGCHLD
mysignal.c
#include#include #include #include #include #include #include #include void handler(int signum){ static int count = 0; count++; printf("hello i'm signal %d,count = %d\n",signum,count);}void child_process(int signum){ puts("i'm process my child"); wait(NULL);}int main(int argc, char *argv[]){ int i; printf("pid = %d\n",getpid()); for(i = 1;i <= 64;i++) { if(SIG_ERR == signal(i,handler)) printf("error = %d\n",i); }//. signal(17,child_process); pid_t pid = fork(); if(pid == 0) { printf("child pid = %d\n",getpid()); sleep(2); exit(0); } // wait(NULL); getchar(); return 0;}
在终端编译链接运行. 结果如下:
上面有4个error, 对应的那4个信号不能设置处理函数!!!
下面列出信号对应的具体数字:
另一个信号注册函数sigaction(). 使用举例如下:
mysigaction.c
#include#include #include #include #include #include #include #include char *p = NULL; void test() { puts("get memory..."); p = malloc(100); sleep(2); puts("free memory..."); free(p); } void handler(int signum) { test(); } int main(int argc, char *argv[]) { struct sigaction act; act.sa_handler = handler; act.sa_flags = SA_NOMASK; sigaction(SIGINT,&act,NULL); getchar(); return 0; }
编译链接运行. 执行结果如下:
直接按回车, 只会打印一行空隔. 按"ctrl+c"执行信号处理.
信号异步产生, 可以将其类比为MCU程序中的中断处理. 其中调用的函数, 若在其他地方也调用, 则要求是可重入的(前面信号处理中的打印语句!!!).