进程间通信-信号(postgresql信号理解)

1、例子1

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void test(int sig)
{
    printf("\n test: I got signal %d\n",sig);
	(void)signal(SIGINT,SIG_DFL);//将SIGINT信号处理方式改成默认,即退出
}
int main()
{
    (void)  signal(SIGINT,test);
	while(1){
	    printf("hello main\n");
		sleep(1);
	}
	return 0;
}
[root@localhost home]# ./sigtest
hello main
hello main
hello main

 test: I got signal 2
hello main
hello main

第一次按下终止命令(ctrl+c)时,进程并没有被终止,面是输出test:I got signal 2,因为SIGINT的默认行为被signal函数改变了,当进程接受到信号SIGINT时,它就去调用函数test去处理,注意test函数把信号SIGINT的处理方式改变成默认的方式,所以当你再按一次ctrl+c时,进程就像之前那样被终止了。

2、例子2

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void test(int sig)
{
    printf("\n test: I got signal %d\n",sig);
	//(void)signal(SIGINT,SIG_DEL);
}
int main()
{
    struct sigaction act;
	act.sa_handler=test;
	sigemptyset(&act.sa_mask);
	act.sa_flags=SA_RESETHAND;
	sigaction(SIGINT,&act,0);
	while(1)
	{
	    printf("hello main\n");
		sleep(1);
	}
	return 0;
}

结果:

[root@localhost home]# ./sigt1
hello main
hello main
hello main

 test: I got signal 2
hello main
hello main

3、关于信号集函数,参考

https://blog.csdn.net/ljianhui/article/details/10130539

猜你喜欢

转载自blog.csdn.net/yanzongshuai/article/details/81050786