您的位置:首页 > 其它

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

2015-04-25 22:26 281 查看
       对于程序员来说, 代码比文字有趣多了, 所以我们少说废话, 多玩代码。 我们先来看一个简单的多线程程序(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实际上就是一个回调函数。

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: