[hb@localhost code_test]$ cat sig.c
#include int main()
{while (1) {printf("I am a process, I am waiting signal!\n");sleep(1);}
}[hb@localhost code_test]$ . / sig
I am a process, I am waiting signal!
I am a process, I am waiting signal!
I am a process, I am waiting signal!^ C
[hb@localhost code_test]$
#include
#include void handler(int sig)
{printf("catch a sig : %d\n", sig);
}int main()
{signal(2, handler);while (1);return 0;
}[hb@localhost code_test]$ . / sig
^ Ccatch a sig : 2
^ Ccatch a sig : 2
^ Ccatch a sig : 2
^ Ccatch a sig : 2
^ \Quit(core dumped)
[hb@localhost code_test]$
7.4.2 模拟一下野指针异常
//默认行为
[hb@localhost code_test]$ cat sig.c
#include
#include void handler(int sig)
{printf("catch a sig : %d\n", sig);
}int main()
{//signal(SIGSEGV, handler);sleep(1);int* p = NULL;*p = 100;while (1);return 0;
}
[hb@localhost code_test]$ . / sig
Segmentation fault(core dumped)
[hb@localhost code_test]$//捕捉行为
[hb@localhost code_test]$ cat sig.c
#include
#include void handler(int sig)
{printf("catch a sig : %d\n", sig);
}int main()
{//signal(SIGSEGV, handler);sleep(1);int* p = NULL;*p = 100;while (1);return 0;
}
[hb@localhost code_test]$ . / sig
[hb@localhost code_test]$ . / sig
catch a sig : 11
catch a sig : 11
catch a sig : 11
#include
int sigemptyset(sigset_t *set);
int sigfillset(sigset_t *set);
int sigaddset (sigset_t *set, int signo);
int sigdelset(sigset_t *set, int signo);
int sigismember(const sigset_t *set, int signo);
[hb@localhost code_test]$ cat sig.c
#include
#include int flag = 0;void handler(int sig)
{printf("chage flag 0 to 1\n");flag = 1;
}int main()
{signal(2, handler);while (!flag);printf("process quit normal\n");return 0;
}[hb@localhost code_test]$ cat Makefile
sig : sig.c
gcc - o sig sig.c # - O2
.PHONY : clean
clean :
rm - f sig[hb@localhost code_test]$ . / sig
^ Cchage flag 0 to 1
process quit normal
标准情况下,键入 CTRL-C ,2号信号被捕捉,执行自定义动作,修改 flag=1 , while 条件不满足,退出循环,进程退出。
[hb@localhost code_test]$ cat sig.c
#include
#include int flag = 0;void handler(int sig)
{printf("chage flag 0 to 1\n");flag = 1;
}int main()
{signal(2, handler);while (!flag);printf("process quit normal\n");return 0;
}[hb@localhost code_test]$ cat Makefile
sig : sig.c
gcc - o sig sig.c - O2
.PHONY : clean
clean :
rm - f sig[hb@localhost code_test]$ . / sig
^ Cchage flag 0 to 1
^ Cchage flag 0 to 1
^ Cchage flag 0 to 1
优化情况下,键入 CTRL-C ,2号信号被捕捉,执行自定义动作,修改 flag=1 ,但是 while 条件依旧满足,进程继续运行!但是很明显flflag肯定已经被修改了,但是为何循环依旧执行?很明显, while 循环检查的flflag,并不是内存中最新的flflag,这就存在了数据二异性的问题。 while 检测的flflag其实已经因为优化,被放在了CPU寄存器当中。如何解决呢?很明显需要 volatile。
[hb@localhost code_test]$ cat sig.c
#include
#include volatile int flag = 0;void handler(int sig)
{printf("chage flag 0 to 1\n");flag = 1;
}int main()
{signal(2, handler);while (!flag);printf("process quit normal\n");return 0;
}[hb@localhost code_test]$ cat Makefile
sig : sig.c
gcc - o sig sig.c - O2
.PHONY : clean
clean :
rm - f sig[hb@localhost code_test]$ . / sig
^ Cchage flag 0 to 1
process quit normal