黑馬《linux系統程式設計》學習筆記(從56到60)
阿新 • • 發佈:2019-01-01
五十六. setitimer定時器函式的使用
五十七. 阻塞訊號集和未決訊號集的關係
比如說我們要阻塞某些程序,先在自定義訊號集中指定0或者1,再把自定義訊號集,寫進阻塞訊號集。
五十八. 讀當前程序的未決訊號集
這裡首先是signal_set.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <signal.h> int main(int argc, const char* argv[]) { //每隔1s賭一次記憶體的未決訊號集 while(1) { sigset_t pendset; sigpending(&pendset); //1~31 for(int i=1;i<32;i++) { //對每一個訊號一次判斷 if(sigismember(&pendset,i)) { printf("1"); } else { printf("0"); } } printf("\n"); sleep(1); } return 0; }
執行一下這個程式
[[email protected]_0_15_centos 7Day]# vim signal_set.c
[[email protected]_0_15_centos 7Day]# ls
abort.c alarm_uncle.c kill.c setitimer.c sigmaks.c signal_set.c
alarm.c homework raise.c sigaction.c signal.c thread_attr.c
[[email protected]_0_15_centos 7Day]# gcc signal_set.c -std=gnu99
[ [email protected]_0_15_centos 7Day]# ./a.out
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
0000000000000000000000000000000
顯然這裡由於沒有訊號阻塞,所以未決訊號集裡,全部是0
五十九. 設定訊號阻塞
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <signal.h> int main(int argc, const char* argv[]) { //手動遮蔽訊號 //自定義訊號集集合 sigset_t myset; //清空集合 sigemptyset(&myset); //新增要阻塞的訊號 sigaddset(&myset,SIGINT); sigaddset(&myset,SIGQUIT); sigaddset(&myset,SIGKILL); //自定義集合資料設定給核心的阻塞訊號集 sigprocmask(SIG_BLOCK, &myset, NULL); //每隔1s賭一次記憶體的未決訊號集 while(1) { sigset_t pendset; sigpending(&pendset); //1~31 for(int i=1;i<32;i++) { //對每一個訊號一次判斷 if(sigismember(&pendset,i)) { printf("1"); } else { printf("0"); } } printf("\n"); sleep(1); } return 0; }
六十. signal訊號捕捉函式
signal.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <signal.h>
void myfunc(int sig)
{
printf("cathc you signal: %d\n", sig);
}
int main(int argc, const char* argv[])
{
// 註冊訊號捕捉函式
signal(SIGINT, myfunc);
while(1)
{
sleep(3);
printf("hello!\n");
}
return 0;
}
執行結果:
[[email protected]_0_15_centos 7Day]# vim signal.c
[[email protected]_0_15_centos 7Day]# gcc signal.c
[[email protected]_0_15_centos 7Day]# ./a.out
hello!
hello!
^Ccathc you signal: 2
hello!
^Ccathc you signal: 2
hello!
^Ccathc you signal: 2
hello!
hello!
^Ccathc you signal: 2
hello!
^Ccathc you signal: 2
hello!
^Ccathc you signal: 2
hello!
^Ccathc you signal: 2
hello!
hello!
hello!