在Linux中,一个信号就是一条小信息,它通知进程系统中发生了某种类型的事件。在Linux中支持30种不同类型的信号。以下涉及的信号主要有:SIGALRM,SIGINT,SIGCHLD,SIGUSR1
alarm是发送SIGALRM信号。
/*****************************************************************************/
void handler(int sig){
static int beeps = 0;
printf("BEEP\n");
if(++beeps < 5)
{
alarm(1);
//;
}
else
{
printf("BOOM\n");
exit(0);
}
}
void learn_alarm_signal(void) //send signal
{
signal(SIGALRM, handler);
alarm(1); //1s send SIFGALRM to handler
while(1)
{
;
}
exit(0);
}
/************************************************************************************/
接受SIGINT信号
/**********************************************************************************/
void learn_recieve_signal(void){
if(signal(SIGINT, handler) == SIG_ERR)
{
printf("signal error\n");
}
pause();
exit(0);
}
/***********************************************************************************/
信号阻塞处理
/**********************************************************************************/
void handler1(int sig){
pid_t pid;
if((pid = waitpid(-1, NULL, 0)) < 0)
{
printf("waitpid error\n");
}
printf("handler reaper child %d\n", pid);
sleep(2);
return;
}
void learn_signal_process(void)
{
int i, n;
char buf[100];
if(signal(SIGCHLD, handler1) == SIG_ERR)
{
printf("signal error\n");
}
for(i = 0;i < 3; ++i)
{
if(fork() == 0)
{
printf("hello from child %d \n", (int)getpid());
sleep(1);
exit(0);
}
}
//STDIN_FILENO就是标准输入设备(一般是键盘)的文件描述符
if((n = read(STDIN_FILENO, buf, sizeof(buf))) < 0)
{
if(errno != EINTR)
{
printf("read error\n");
}
}
printf("parent processing inpput\n");
while(1)
{
;
}
exit(0);
}
/**************************************************************************************/
用户自定义信号使用
/*************************************************************************************/
pid_t pid;int counter = 2;
void handler2(int sig)
{
counter = counter - 1;
printf("handler2:%d, pid:%d\n", counter, (int)getpid());
fflush(stdout);
exit(0);
}
void exe_signal_proc(void)
{
signal(SIGUSR1, handler2);
printf("exe_signal_proc:%d, pid:%d\n",counter, (int)getpid());
fflush(stdout);
if((pid = fork()) == 0)
{
while(1)
{
;//printf("hello\n");
}
}
kill(pid, SIGUSR1);
waitpid(-1, NULL, 0);
counter = counter + 1;
printf("exe_signal_proc:%d,pid:%d\n", counter, (int)getpid());
exit(0);
}
/************************************************************************************************/