#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> void sig_thread_func(int sig) { 	printf("sig_thread_func : sig = %dn", sig); } void sig_func(int sig) { 	printf("sig_func : sig = %dn",sig); } void *func1(void *arg) {     signal(SIGUSR1, sig_thread_func);   //线程1先运行,设置了signal 	sigset_t set; 	sigfillset(&set); 	sigdelset(&set, SIGUSR1); 	pthread_sigmask(SIG_SETMASK, &set, NULL);//线程1屏蔽了除了SIGUSR1外的所有信号 	printf("pthread 1 runn"); 	int i; 	for(i = 0; i < 7; ++i) 	{ 		printf("1...n"); 		sleep(1); 	} 	return 0; } void *func2(void *arg) { 	printf("pthread 2 runn"); 	int i; 	for(i = 0; i < 7; ++i) 	{ 		printf("2...n"); 		sleep(1); 	} 	return 0; } int main() { 	pthread_t tid1, tid2; 	pthread_create(&tid1, NULL, func1, NULL); 	pthread_create(&tid2, NULL, func2, NULL); 	sleep(1); 	signal(SIGUSR1, sig_func);  //覆盖了线程1设置的signal     //向线程1发送SIGUSR1,SIGUSR2 	sleep(1); 	pthread_kill(tid1, SIGUSR1);//调动handler 	sleep(1); 	pthread_kill(tid1, SIGUSR2);//屏蔽了,无响应     //向线程2发送SIGUSR1,SIGUSR2 	sleep(1); 	pthread_kill(tid2, SIGUSR1);//调用handler 	sleep(1); 	//pthread_kill(tid2, SIGUSR2);//会终止进程,是进程! 	sigset_t set; 	sigfillset(&set); 	sigprocmask(SIG_SETMASK, &set, NULL);//进程屏蔽了所有信号 	sleep(1); 	kill(getpid(), SIGUSR1);//调动handler?其实是线程1响应的 	pthread_join(tid1, NULL); 	pthread_join(tid2, NULL); 	return 0; } 
运行结果: 
[cpp] view plaincopyprint? 01.huangcheng@ubuntu:~$ ./a.out   02.pthread 2 run   03.2...   04.pthread 1 run   05.1...   06.2...   07.1...   08.2...   09.sig_func : sig = 10   10.1...   11.2...   12.1...   13.sig_func : sig = 10   14.2...   15.1...   16.2...   17.1...   18.2...   19.sig_func : sig = 10   20.1...   huangcheng@ubuntu:~$ ./a.out pthread 2 run 2... pthread 1 run 1... 2... 1... 2... sig_func : sig = 10 1... 2... 1... sig_func : sig = 10 2... 1... 2... 1... 2... sig_func : sig = 10 1...                         (编辑:滁州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |