线程与信号

1.子线程会继承主线程信号处理配置,故信号配置可以全部放在主线程内。

2.同一信号多次触发或者嵌套触发不会嵌套执行。

3.不同信号可以嵌套触发执行。

4.kill()触发的信号由进程(主线程)执行,pthread_kill()触发的信号由参数指定的线程执行。

下面是测试例子:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


static void* thread_func(void * args)
{
	pthread_t tid = pthread_self();
	printf("[child] thread id:%lu\r\n", tid);
	printf("[child] thread sleep\r\n");
	sleep(30);
	printf("[child] thread exit\r\n");
	return 0;
}

static void signal_main_func(int signo, siginfo_t *info, void *data)
{
	pthread_t tid = pthread_self();
	printf("[signal-mian] signal:[%d]. current thread id:%lu, \r\n", signo, tid);
	
	printf("[signal-mian] signal sleep\r\n");
	sleep(20);
	printf("[signal-mian]signal exit\r\n");
}

static void signal_child_func(int signo, siginfo_t *info, void *data)
{
	pthread_t tid = pthread_self();
	printf("[signal-child] signal:[%d]. current thread id:%lu\r\n", signo, tid);
	
	printf("[signal-child] child signal sleep\r\n");
	sleep(2);
	printf("[signal-child] child signal exit\r\n");
	
}

static void signal_timeout(int n)
{
	pthread_t tid = pthread_self();
	printf("[signal-timer] timeout[%d]. current thread id:%lu\r\n", n,tid);
}

void init_timer(int ms)
{
	struct sigaction act;
	struct itimerval value;
	
	act.sa_handler = signal_timeout;
	act.sa_flags = SA_RESTART;
	sigemptyset(&act.sa_mask);
	sigaction(SIGALRM, &act, NULL );
	
	
	value.it_value.tv_sec = ms/1000;
	value.it_value.tv_usec = ms%1000 * 1000;
	value.it_interval = value.it_value;
	setitimer(ITIMER_REAL, &value, NULL );
}

void init_signal(int signo, void* handler)
{
	struct sigaction act;
	act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
	act.sa_flags = SA_SIGINFO;
	sigemptyset(&act.sa_mask);
	sigaction(signo, &act, NULL );
}


int main(int argc, char** argv)
{
	int ret;
	int count = 10;
	pthread_t tid;
	
	tid = pthread_self();
	printf("[main] thread id:%lu\r\n", tid);
	
	init_signal(SIGINT, signal_main_func);
	init_timer(1000);
	init_signal(SIGUSR1, signal_child_func);

	ret = pthread_create(&tid, 0, (void*)thread_func, NULL);
	if (ret < 0) {
		printf("failed to create thread.\r\n");
		return -1;
	}
	pthread_detach(tid);

	
	while(count-- > 0) {
		printf("[main] kill child. child thread id:%lu\r\n", tid);
		pthread_kill(tid, SIGUSR1);
		
		printf("[main] thread sleep. count:%d\r\n", count);
		sleep(3);
	}
	
	printf("[main] thread exit\r\n");
	return 0;
}

执行结果:

线程与信号_第1张图片

 

你可能感兴趣的:(java,开发语言)