用于用户进程与内核进程的通信,一种异步通信机制,
信号是在软件层次上对中断机制的一种模拟
用户进程对信号的响应方式:
忽略信号:对信号不做任何处理,但是有两个信号不能忽略:即SIGKILL及SIGSTOP。
捕捉信号:定义信号处理函数,当信号发生时,执行相应的处理函数。
执行缺省操作:Linux对每种信号都规定了默认操作
kill -l 可以才看系统默认的信号
我们通过注册信号进行使用,具体流程如下
注册信号函数原型
sighandler_t signal(int signum, sighandler_t handler);
sighandler_t 原型追索:
typedef void (*sighandler_t)(int);
<====>
typedef void (*)(int) sighandler_t;
signum 信号类型,
handler 处理函数
1)用户自定义
2)SIG_IGN 忽略
3)SIG_DFL 默认
函数原型:int kill(pid_t pid, int sig);
功能:发送信号给进程组或进程
参数:pid >0 指定进程号发送信号
pid =0 发送信号给与调用进程在同一个进程组的每一个进程
pid =-1 发送信号给允许发送的每一个进程(init除外)
pid <-1 发送信号给进程组ID等于-pid的每一个进程
sig 信号的类型
返回值:成功 0
失败 -1
函数原型: int raise(int sig);
功能:给自己发送信号
参数:sig 信号的类型
返回值:成功 0
失败 非0
以下示例代码演示了无名管道传输数据,添加信号处理
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#define N 64
int main(int argc, const char *argv[])
{
pid_t pid;
int fd[2];
char buf[N] = "";
if(pipe(fd) < 0){
perror("pipe error");
return -1;
}
pid = fork();
if(pid < 0){
perror("fork error");
return -1;
}
else if(pid == 0){
while(1){
fgets(buf, N, stdin);
buf[strlen(buf) - 1] = '\0';
write(fd[1], buf, strlen(buf));
if(strncmp(buf, "quit", 4) == 0){
kill(getppid(), SIGKILL);
raise(SIGKILL);
}
}
}
else{
while(1){
read(fd[0], buf, N);
printf("read:%s\n", buf);
}
}
return 0;
}