Linux c signal

#include <stdio.h>
#include <signal.h>

static void signal_handle(int sig) {
	
	printf("sig=%d\n",sig);
	if(sig==SIGKILL)
	{

		printf("程序被强制关闭了");
	}
	printf("signal_handle end\n");

}
int main(int argc, char *argv[])
{

	signal(SIGHUP, signal_handle);
	signal(SIGPIPE, signal_handle);
	signal(SIGTERM, signal_handle);
	signal(SIGQUIT, signal_handle);
	signal(SIGINT, signal_handle);
	signal(SIGABRT, signal_handle);
	signal(SIGKILL,signal_handle);
	signal(SIGSEGV,signal_handle);
	signal(SIGSTOP,signal_handle);
	signal(SIGCONT,signal_handle);
	/* The following signals are defined by Standard C.

	Macro	Meaning
	SIGABRT	Termination error
	SIGFPE	Floating-point error
	SIGILL	Bad instruction
	SIGINT	User pressed CTRL-C
	SIGSEGV	Illegal memory access
	SIGTERM	Terminate program   
	*/
	
	raise(SIGTERM);
	raise(SIGQUIT);//发送退出信号
	raise(SIGCONT);//发送继续信息
	raise(SIGSEGV);//发送信号Segmentation fault
	raise(SIGSTOP);//sends the specified by signal to the executing program
	
	//raise(SIGKILL);//发送被关闭信号,该信号不能给屏蔽,程序会直接退出。
	


	fflush(stdout); /* <============== Put a breakpoint here */
	return 0;
}
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
static void sig_quit(int);
//http://blog.csdn.net/fjb2080/article/details/5174306
//其中SIGKILL(9)与SIGSTOP(19)是不能捕获的
int main(void)
{
	sigset_t newmask, oldmask, pendingmask;
	//设置对信号SIGQUIT的处理函数
	if (signal(SIGQUIT, sig_quit) == SIG_ERR)
	{
		fprintf(stderr, "can't catch SIGQUIT\n");
		exit(1);
	}
	//设置一个空的信号集
	sigemptyset(&newmask);
	sigaddset(&newmask, SIGQUIT); // 在这个信号集中增加SIGQUIT信号

	//在当前进程中增加newmask信号集作为屏蔽信号集,oldmask返回当前进程的信号集
	if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) 
	{
		fprintf(stderr, "SIG_BLOCK error\n");
		exit(1);
	}
	sleep(5);
	//返回当前进程信号集
	if (sigpending(&pendingmask) < 0)
	{
		fprintf(stderr, "sigpending error\n");
		exit(1);
	}
	//检查SIGQUIT信号是否在当前信号集中
	if (sigismember(&pendingmask, SIGQUIT))
		printf("\nSIGQUIT pending\n");
	//恢复进程的信号集
	if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
	{
		fprintf(stderr, "SIG_SETMASK error\n");
		exit(1);
	}
	printf("SIGQUIT unblocked\n");
	sleep(5);
	exit(0);
}
static void sig_quit(int signo)
{
	printf("caught SIGQUIT\n");
	//恢复进程对SIGQUIT的默认处理
	if (signal(SIGQUIT, SIG_DFL) == SIG_ERR)
	{
		fprintf(stderr, "can't reset SIGQUIT\n");
		exit(0);
	}
}

http://m-ittrue.iteye.com/blog/1728451

你可能感兴趣的:(Linux c signal)