免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: dongpy
打印 上一主题 下一主题

【求助】主线程如何杀死正在执行的子线程? [复制链接]

论坛徽章:
0
11 [报告]
发表于 2006-08-25 21:22 |只看该作者
system("
killall pid
or
kill -9 pid
")

论坛徽章:
0
12 [报告]
发表于 2007-03-02 09:00 |只看该作者
使用楼上的方法的话整个进程都被杀掉了!!!

论坛徽章:
0
13 [报告]
发表于 2007-03-02 09:36 |只看该作者
看看下面这段,是否有帮助。

Never terminate the thread from outside the thread. Always terminate the thread from within the thread itself. If the thread isn't allowed to terminate itself, it will continue to consume resources even after the app is closed. Resources being memory for stack space and thread local storage, objects that are created by the thread, file buffers, etc.

Your thread will typically be running in a loop. If it's not, it will terminate automatically when it hits a return statement in the thread function or at the end of the thread function.
While looping in the thread function there are a couple of things you can do.

1. Periodically check the status of a flag variable that indicates to exit the thread (The flag can be set externally to the thread itself), and exit the loop once the flag is set.

2. Periodically check for an event to have occurred using one of the wait functions.

论坛徽章:
0
14 [报告]
发表于 2007-03-02 12:46 |只看该作者
我是这样做的,
fork进程以后,记住子进程的进程号pid,然后kill(pid,9);就可以了。

或者通过管道向子进程发送自杀信号,子进程在循环中检测信号,一旦检测到主进程要求子进程“自杀”,那么子进程就可以exit了


  1. //子进程,检测信号
  2.        while(1)
  3.         {
  4.             pipe_read(CMDPIPE,pipe_info);//读取管道
  5.             if(pipe_info->sig_term == 1) //
  6.             {
  7.                 free(pipe_info);
  8.                 kill(pid,9);//同时结束另外一个子进程
  9.                  return(1);//自身退出
  10.             }
  11.             sleep(1);
  12.         }
复制代码

[ 本帖最后由 jemy.zhang 于 2007-3-2 12:55 编辑 ]

论坛徽章:
0
15 [报告]
发表于 2007-03-02 13:39 |只看该作者
原帖由 jemy.zhang 于 2007-3-2 12:46 发表
我是这样做的,
fork进程以后,记住子进程的进程号pid,然后kill(pid,9);就可以了。

或者通过管道向子进程发送自杀信号,子进程在循环中检测信号,一旦检测到主进程要求子进程“自杀”,那么子进程就可以exit了 ...

楼主是说要杀子线程吧, 不是子进程

论坛徽章:
0
16 [报告]
发表于 2007-03-02 13:50 |只看该作者
哦。。。。看错了,呼呼呼~

不过有谁能说说进程和线程的区别啊?忘记了似乎

论坛徽章:
0
17 [报告]
发表于 2007-03-03 01:09 |只看该作者
原帖由 caijimin 于 2007-3-2 09:36 发表
看看下面这段,是否有帮助。

Never terminate the thread from outside the thread. Always terminate the thread from within the thread itself. If the thread isn't allowed to terminate itself, it will ...



这个已经说得相当的明白了。

论坛徽章:
0
18 [报告]
发表于 2007-03-13 14:55 |只看该作者
楼主在线程函数死循环里面加上cancellation函数例如pthread_testcancel,因为线程创建出来初始状态是PTHREAD_CANCEL_DEFERRED的,也就是线程需要运行到cancellation point才会响应其他线程的cancel request,不知道说明白没有.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP