kill函数用于向任何进程组或进程发送信号。
1.kill函数
#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int signum);
注意:使用 kill() 函数发送信号,接收信号进程和发送信号进程的所有者必须相同,或者发送信号进程的所有者是超级用户。
参数: pid: 取值有 4 种情况:
signum: 信号的编号,这里可以填数字编号,也可以填信号的宏定义,可以通过命令kill -l ("l" 为字母)进行相应查看。
返回值: - 成功:0 - 失败:-1
实例: 本来父子进程各自每隔一秒打印一句话,3 秒后,父进程通过 kill() 函数给子进程发送一个中断信号 SIGINT( 2 号信号),最终,子进程结束,剩下父进程在运行。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
int main(int argc, char *argv[])
{
pid_t pid;
int i = 0;
pid = fork(); // 创建进程
if( pid < 0 ){ // 出错
perror("error to create process:");
}
if(pid == 0){ // 子进程
while(1){
printf("I am son!\n");
sleep(1);
}
}else if(pid > 0){ // 父进程
while(1){
printf("I am father!\n");
sleep(1);
i++;
if(3 == i){// 3秒后
kill(pid, SIGINT); // 给子进程 pid ,发送中断信号 SIGINT
// kill(pid, 2); // 等级于kill(pid, SIGINT);
}
}
}
return 0;
}
运行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
I am father!
I am son!
I am father!
I am son!
I am father!
I am son!
I am father!
I am father!
I am father!
...
我们也可以使用kill杀死某个进程。例如:
#9表示SIGKILL,该进程不允许自定义和忽略
kill -9 进程号