Linux 基本语句_12_信号

用途:

信号可以直接进行用户进程与内核进程之间的交互

特性:

对于一个进程,其可以注册或者不注册信号,不注册的信号,进程接受后会按默认功能处理,对于注册后的信号,进程会按自定义处理


自定义信号:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>void handler(int arg){if(arg == SIGINT){puts("catch the SIGINT"); // 如果接受此信号打印.... }
}int main(int argc, const char * argv[]){if(signal(SIGINT, handler) == SIG_ERR){ // 注册SIGINT信号,接受后按handler要求执行,键盘输入Ctrl + C可接受 printf("signal error");exit(1);}if(signal(SIGTSTP, SIG_IGN) == SIG_ERR){ // SIG_IGN即对SIGTSTP忽略 printf("signal error");exit(1);}while(1){sleep(1);printf("hello world\n");}return 0;
}

效果:

在这里插入图片描述


程序发送信号:

上述发送信号是按键给程序发送信号,下面就是进程进程之间发送信号

在这里插入图片描述

有将信号发送给其他进程也有将信号发送给本身

代码:

#include <stdio.h>
#include <signal.h>int main(int argc, const char * argv[]){pid_t pid;pid = fork(); // 若pid大于0则其为创建的子进程pid if(pid < 0){printf("fork error\n");}else if(pid == 0){  printf("the child process living\n");while(1);}else{sleep(3);printf("the parent process online\n");kill(pid, SIGKILL); // 结束子进程printf("child be stoped by parent\n");printf("parent stoped himself\n");raise(SIGKILL); // 结束本身 }return 0;
}

效果:

在这里插入图片描述


闹钟定时:

通过闹钟定时关闭进程

代码:

#include <stdio.h>
#include <unistd.h>int main(int argc, const char * argv[]){unsigned int ret;ret = alarm(8);printf("ret1 = %d\n", ret);sleep(3);ret = alarm(3);printf("ret2 = %d\n", ret);while(1);return 0;
}

效果:

在这里插入图片描述