1、信号是内容受限的一种异步通信机制
2、信号由谁发出
3、信号由谁处理、如何处理
1、signal 函数介绍
原型:sighandler_t signal(int signum,sighandler_t handler),typedef void (*sighandler_t)(int)2、用 siganl 函数处理 SIGINT 信号
#include
#include
#include
typedef void (*sighandler_t)(int);//宏函数指针
void func(int sig)//信号捕获函数
{
if(SIGINT!=sig){
return;printf("func for signal:%d.\n",sig);
}
}
int main(void)
{
sighandler_t ret=(sighandler_t)-2;
//===选择信号处理的方式
//ret=signal(SIGINT,SIG_DFL);//指定信号SIGINT为默认处理方式
//ret=signal(SIGINT,SIG_IGN);//指定信号SIGINT为忽略处理
ret=signal(SIGINT,func);
if (SIG_ERR == ret) {
perror("signal error"); exit(-1);
}
printf("before while(1)\n");
while(1);
printf("after while(1)\n");
return 0;
}
3、sigaction 函数介绍
int sigaction(int signum,const struct sigaction* act,struct sigaction* oldact);#include
#include
#include
static void sig_handler(int sig)
{
printf("Received signal: %d\n", sig);
}
int main(int argc, char *argv[])
{
struct sigaction sig = {0};
int ret;
sig.sa_handler = sig_handler;
sig.sa_flags = 0;
ret = sigaction(SIGINT, &sig, NULL);
if (-1 == ret) {
perror("sigaction error");
exit(-1);
}
/* 死循环 */
for ( ; ; ) { }
exit(0);
}
1.alarm 函数
unsigned int alarm(unsigned int seconds)
#include
#include
#include
void func(int sig)
{
if(sig==SIGALRM)
printf("alarm happened.\n");
}
int main(void)
{
unsigned int ret=-1;
struct sigaction act={0};
act.sa_handler=func;
sigaction(SIGALRM,&act,NULL);
//signal(SIGALRM,func);
ret=alarm(5);printf("ret=%d.\n",ret);
while(1);return 0;
}
2.pause 函数
int pause(void)
3.使用 alarm 和 pause 来模拟 sleep
#include
#include
#include
void func(int sig)
{
printf("Received signal: %d\n", sig);
}
void mysleep(unsigned int seconds);
int main(void)
{
printf("before mysleep.\n");
mysleep(3);
printf("after mysleep.\n");
return 0;
}
void mysleep(unsigned int seconds)
{
struct sigaction act={0};
act.sa_handler=func;//绑定信号捕获函数
sigaction(SIGALRM,&act,NULL);
alarm(seconds);
pause();
}
若要详细了解linux信号,看我另一篇博客linux信号详解