利用thread来简要模拟signal函数功能

       对于程序员来说, 代码比文字有趣多了, 所以我们少说废话, 多玩代码。 我们先来看一个简单的多线程程序(test.c):

#include <stdio.h>  
#include <pthread.h> //编译的时候要用gcc test.c -lpthread

void sig_callback()
{
	printf("taoge is entering ENTER\n");
}

void *threadFun(void *p)
{
	while(1)
	{
		getchar();
		sig_callback();
	}
	
	return NULL;
}

int main()
{
	pthread_t id;
	pthread_create(&id, NULL, threadFun, NULL);

	while(1)
	{
		static int i = 0;
		printf("%d\n", i++);
		sleep(1);
	}
	
	return 0;  
}  

      上面的程序, 如果直接用gcc test.c编译, 则有错, 请用gcc test.c -lpthread

      我们看到, 主线程负责做正事, threadFun线程负责处理用户输入, 两个线程的指责分明, 互不骚扰。 线程threadFun实际上在密切地监听ENTER事件, 此时sig_callback实际上就是一个回调函数。


       好, 我们来看看signal函数吧:

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

void sig_callback()
{
	printf("the user is entering Ctrl C\n");
}

int main()
{  
	if(SIG_ERR == signal(SIGINT, sig_callback))
	{
		printf("error0\n");
		return 1;
	}

	while(1)
	{
		static int i = 0;
		printf("%d\n", i++);
		sleep(1);
	}
	
	return 0;  
}  
      当程序运行时, 程序实际上就在随时等待SIGINT信号(由ctrl c产生), 一旦有ctrl c, 则立即调用sig_callback, 此时sig_callback实际上就是一个回调函数。


      通过对比上面两个简单的程序, 我们看到了太多的类似, 至于每个人感受到了什么, 则是因人而异的羡慕






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值