Linux系统信号学习笔记


在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);
}
/************************************************************************************************/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值