利用thread来简要模拟signal函数功能
2015-04-25 22:26
281 查看
对于程序员来说, 代码比文字有趣多了, 所以我们少说废话, 多玩代码。 我们先来看一个简单的多线程程序(test.c):
上面的程序, 如果直接用gcc test.c编译, 则有错, 请用gcc test.c -lpthread
我们看到, 主线程负责做正事, threadFun线程负责处理用户输入, 两个线程的指责分明, 互不骚扰。 线程threadFun实际上在密切地监听ENTER事件, 此时sig_callback实际上就是一个回调函数。
好, 我们来看看signal函数吧:
通过对比上面两个简单的程序, 我们看到了太多的类似, 至于每个人感受到了什么, 则是因人而异的
。
#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实际上就是一个回调函数。
通过对比上面两个简单的程序, 我们看到了太多的类似, 至于每个人感受到了什么, 则是因人而异的
。
相关文章推荐
- 创建函数利用可变参数列表的形式模拟实现printf的功能
- 行式填报表利用JS函数实现批量删除功能
- 利用Keybd_event()函数模拟键盘输入
- C++学习 【4.1】 利用函数实现指定的功能---函数,函数的形式,函数参数
- C++学习 【4.3】 利用函数实现指定的功能---内置函数
- 自己模拟strcmp库函数写的功能函数my_strcmp实现strcmp的功能,完整代码
- 利用 IIdentifyDialog 模拟ArcMap工具里面 Identify功能进行要素查询
- 利用接口与类实现类似于函数指针的功能
- 利用PHP绘图函数实现简单验证码功能的方法
- C++学习 【4.2】 利用函数实现指定的功能---函数的调用
- 利用Windows的API实现C语言的MD5函数功能
- 网络编程(13)—— 利用信号处理函数signal和sigaction销毁僵尸进程
- 利用多线程模拟卖票的功能
- 用Python最原始的函数模拟eval函数的浮点数运算功能
- Linux下利用signal函数处理ctrl+c等信号
- linux下利用系统函数实现rm -rf的功能!
- Java利用接口和类来实现类似函数指针的功能
- 利用陀螺仪模拟简易的SLAM功能(仅旋转)
- JavaScript利用构造函数和原型的方式模拟C#类的功能
- 利用C++11的function和bind功能,实现QStandardItemModel的通用遍历函数