网络服务器软件开发/中间件开发,关注ACE/ICE/boost

C++博客 首页 新随笔 联系 聚合 管理
  152 Posts :: 3 Stories :: 172 Comments :: 0 Trackbacks

代码操作步骤如下:

[tqg@localhost test]$ vi test.cpp


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

void signal_handler(int sig)
{
        printf("catch signal: %d,thread id = %u\n",sig,pthread_self());
        pthread_exit(0);
}

void* thread_handler(void*arg)
{
        signal(SIGQUIT,signal_handler);

        printf("thread arg = %s\n",(char*)arg);

        sleep(10);
        printf("in thread\n");

        return (void*)0;
}

int main()
{
        char* pArg = "hello";
        pthread_t tid;
        pthread_create(&tid,NULL,thread_handler,pArg);

        printf("main thread id = %u\n",pthread_self());
        sleep(2);

        printf("killing now\n");
        pthread_kill(tid,SIGQUIT);

        sleep(20);

        printf("exit main now\n");

        return 0;
}
~
~
~
~
"test.cpp" 42L, 648C written
[tqg@localhost test]$ g++ -o test test.cpp -lpthread
[tqg@localhost test]$ ./test
main thread id = 3086875296
thread arg = hello
killing now
catch signal: 3,thread id = 3086871472
exit main now
[tqg@localhost test]$

可以看出,信号处理函数的执行是在要捕获信号的子线程thread_handler的上下文中执行的。

posted on 2009-01-15 11:39 true 阅读(2381) 评论(6)  编辑 收藏 引用 所属分类: C++基础linux

Feedback

# re: linux下信号处理函数实现的一点理解[未登录] 2009-01-15 12:59 steven
昏倒,
pthread_kill(tid,SIGQUIT);这是什么呀,这是向线程发信号,而不是向进程发。
你要测试你需要的效果,请用kill(getpid(),SIGQUIT);  回复  更多评论
  

# re: linux下信号处理函数实现的一点理解 2009-01-15 14:51 true
没太明白楼上的意识哦,我就是要向线程发送信号哦,“该线程先获得cpu时间”的描述有误解?确切些是进程中的线程获得了cpu时间  回复  更多评论
  

# re: linux下信号处理函数实现的一点理解 2009-01-24 06:53 ooo
愣是没看懂。。。lz你太有才了。。。

你自己create了一个thread,然后发signal给刚建好的thread--到此为止一切正常

但是你怎么得出结论,这是内核为你创建的一个线程?这分明是你自己刚创建的啊!

你还是别学编程了。。。  回复  更多评论
  

# re: linux下信号处理函数实现的一点理解 2009-02-02 16:05 true
@ooo
我表达的不够清楚?“可以推断为,当内核(?)捕获到信号时,启动了一个更高优先级的线程,该线程先获得cpu时间,有他来执行信号处理函数。”,我是说的执行signal_handler的线程,不是thread_handler!  回复  更多评论
  

# re: linux下信号处理函数实现的一点理解 2009-03-10 11:02 bert
楼主啊,这是你自创的结论吧。。。
在main函数的printf("main thread id = %u\n",pthread_self());
下面添加一行:
printf("child thread id = %u\n", tid);
看看结果。
再思考一下吧。。  回复  更多评论
  

# re: linux下信号处理函数实现的一点理解 2009-03-10 11:24 true
@bert
@ooo
今天又看了下文章,发现自己的错误如此低级,竟然误拿main的id和子线程id进行了比较,谢谢2位,并向大家道歉!文章虽然修改  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理