信号通信
方式:
信号类型:
下面是几种常见的信号:
§ SIGHUP: 从终端上发出的结束信号
§ SIGINT: 来自键盘的中断信号(Ctrl-C)
§ SIGKILL:该信号结束接收信号的进程,杀死进程
§ SIGTERM:kill 命令发出的信号
§ SIGCHLD:子进程停止或结束时通知父进程
§ SIGSTOP:来自键盘(Ctrl-Z)或调试程序的停止执行信号,暂停进程
3.kill
函数的作用:传送信号给指定的进程
函数的原型:int kill(pid_t pid,int sig)
函数的参数:pid > 0 指定的进程的PID
pid = 0 发送给目前进程相同组的所有进程
pid = -1 广播给系统内所有的进程
pid < 0
sig : 信号
返 回 值:成功 0 出错 -1
头 文 件:#include <signal.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int ret;
if((pid=fork()) < 0)
{
perror("fork");
exit(1);
}
if(pid == 0)
{
raise(SIGSTOP);
exit(0);
}
else
{
printf("pid=%d\n", pid);
if((waitpid(pid, NULL, WNOHANG)) == 0)
{
kill(pid,SIGKILL);
printf("kill %d\n", pid);
}
else
{
perror("kill");
}
}
}
4.raise
函数的作用:发送信号给自身
函数的原型:int raise(int sig)
头 文 件:#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
int main()
{
pid_t pid;
int ret;
if((pid= fork()) < 0)
{
printf("Fork error.\n");
exit(-1);
}
if(pid == 0)
{
printf("child (pid:%d) is waiting for any signal\n.", getpid());
raise(SIGSTOP);
exit(0);
}
else
{
if((waitpid(pid, NULL, WNOHANG)) == 0)
{
kill(pid, SIGKILL);
printf("parent kill child process %d\n", pid);
}
waitpid(pid, NULL, 0);
exit(0);
}
}
5.alarm
函数的作用:设置信号传送闹钟
函数的原型:unsigned int alarm(unsigned int seconds)
返 回 值:返回之前闹钟的剩余秒数,如果之前未设闹钟则返回0
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
void handle()
{
printf(“hello!\n”);
}
int main()
{
int i;
signal(SIGALRM,handle);
alarm(5);
for(i = 0; i <= 7; i++)
{
printf(“sleeping...%d\n”,i);
sleep(1);
}
}
6.pause
函数的作用:让进程暂停,直到信号的出现
函数的原型:int pause(void);
返 回 值:-1
头 文 件:#include <unistd.h>
7.signal
函数的作用:设置信号处理方式
函数的原型:void (* signal(int signum,void(*handler)(int))(int)
typedef void(*sighandler_t)(int)
sighandler_t signal(int signum,sighandler_t handler);