黑馬《linux系統程式設計》學習筆記(從51到55)
阿新 • • 發佈:2019-01-01
五十一. kill函式的使用
這裡我們寫一個kill.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[]) { pid_t pid = fork(); if(pid == -1) { perror("fork error"); exit(1); } if(pid > 0) { while(1) { printf("parent process pid = %d\n", getpid()); sleep(1); } } else if(pid == 0) { sleep(2); // 弒父 kill(getppid(), SIGKILL); } return 0; }
執行一下
[[email protected]_0_15_centos 7Day]# ls alarm.c homework raise.c sigaction.c signal.c alarm_uncle.c kill.c setitimer.c sigmaks.c thread_attr.c [[email protected]_0_15_centos 7Day]# gcc kill.c [[email protected]_0_15_centos 7Day]# ./a.out parent process pid = 30669 parent process pid = 30669 parent process pid = 30669 Killed
五十二. kill函式pid引數介紹
五十三. raise和abort函式
寫一個raise.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <signal.h> #include <sys/wait.h> int main(int argc, const char* argv[]) { pid_t pid = fork(); if(pid > 0) { // parent int s; pid_t wpid = wait(&s); printf("child died pid = %d\n",wpid); if(WIFSIGNALED(s)) { printf("term by signal: %d\n", WTERMSIG(s)); } } else if(pid == 0) { raise(SIGINT); // abort(); } return 0; }
執行一下:
[[email protected]_0_15_centos 7Day]# vim raise.c
[[email protected]_0_15_centos 7Day]# ls
alarm.c a.out kill.c setitimer.c sigmaks.c thread_attr.c
alarm_uncle.c homework raise.c sigaction.c signal.c
[[email protected]_0_15_centos 7Day]# gcc raise.c
[[email protected]_0_15_centos 7Day]# ./a.out
child died pid = 12026
term by signal: 2
寫一個abort.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
int main(int argc, const char* argv[])
{
pid_t pid = fork();
if(pid > 0)
{
// parent
int s;
pid_t wpid = wait(&s);
printf("child died pid = %d\n",wpid);
if(WIFSIGNALED(s))
{
printf("term by signal: %d\n", WTERMSIG(s));
}
}
else if(pid == 0)
{
// raise(SIGINT);
abort();
}
return 0;
}
執行一下
[[email protected]_0_15_centos 7Day]# ls
abort.c alarm_uncle.c kill.c setitimer.c sigmaks.c thread_attr.c
alarm.c homework raise.c sigaction.c signal.c
[[email protected]_0_15_centos 7Day]# gcc abort.c
[[email protected]_0_15_centos 7Day]# ./a.out
child died pid = 12434
term by signal: 6
五十四. alarm函式
alarm的文件
寫一個alarm.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, const char* argv[])
{
int ret = alarm(5);
printf("ret = %d\n", ret);
sleep(2);
ret = alarm(2);
printf("ret = %d\n", ret);
while(1)
{
printf("hello\n");
sleep(1);
}
return 0;
}
執行結果
[[email protected]_0_15_centos 7Day]# gcc alarm.c
[[email protected]_0_15_centos 7Day]# ./a.out
ret = 0
ret = 3
hello
hello
Alarm clock
五十五. 計算1s數多少個數