博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
signal信号
阅读量:4311 次
发布时间:2019-06-06

本文共 1931 字,大约阅读时间需要 6 分钟。

信号的学习.

例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程序中的中断处理.  其中调用的函数, 若在其他地方也调用, 则要求是可重入的(前面信号处理中的打印语句!!!).

转载于:https://www.cnblogs.com/zhanglong71/p/5093163.html

你可能感兴趣的文章
Sed&awk笔记之awk
查看>>
DNS泛解析配置
查看>>
Codeforces Round #351 (VK Cup 2016 Round 3, Div. 2 Edition) D Bear and Two Paths
查看>>
Python学习-day1
查看>>
ORA-06512 问题解决
查看>>
hdu 2049 不容易系列之考新郎 && 对错排的详解
查看>>
10个面向程序员的在线编程网站
查看>>
c#设计模式-单例模式(面试题)
查看>>
WPF x名称空间详解
查看>>
pyenv管理多python版本
查看>>
mysql 存储过程和触发器综合例题
查看>>
深度的发现之256个class打平1个id
查看>>
0909我对编译原理的见解
查看>>
lib 和 dll
查看>>
hdu 2042 - 不容易系列之二
查看>>
Linux下设置postgresql数据库开机启动
查看>>
mysql函数技巧整理
查看>>
二叉树
查看>>
IO多路复用--epoll详解
查看>>
[线段树优化应用] 数星星Star
查看>>