是什么导致 pthread 失效?
我正在使用一个多线程程序(使用pthreads),当前创建一个后台线程(PTHREAD_DETACHED),然后调用pthread_exit(0)。 我的问题是该进程随后被列为“已失效”,并且奇怪的是似乎在 /proc 中似乎并不“真正存在”(这破坏了我的调试策略)
我希望满足以下要求:
- 程序应该在 循环和函数 B
- 一旦给定程序 /proc/$pid/exe、/proc/$pid/maps 和 /proc/$pid/fd 的 PID, 就必须可访问(当进程失效时,它们都是空的或无效链接)
- 必须可以像往常一样使用 CTRL+C 和 CTRL+Z 挂起/中断程序
编辑:我犹豫是否要更改程序的界面,以便将 A 放在“主”线程中,将 B 放在“主”线程中生成的线程(它们当前处于相反的方式)。 它能解决问题吗?
i'm working with a multi-threaded program (using pthreads) that currently create a background thread (PTHREAD_DETACHED) and then invokes pthread_exit(0). My problem is that the process is then listed as "defunct" and curiously do not seems to "really exists" in /proc (which defeats my debugging strategies)
I would like the following requirements to be met:
- the program should run function A in a loop and function B once
- given the PID of the program /proc/$pid/exe, /proc/$pid/maps and /proc/$pid/fd must be accessible (when the process is defunct, they are all empty or invalid links)
- it must be possible to suspend/interrupt the program with CTRL+C and CTRL+Z as usual
edit: I hesitate changing the program's interface for having A in the "main" thread and B in a spawned thread (they are currently in the other way). Would it solve the problem ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以挂起等待信号的主进程的执行,或者不分离等待其终止的线程(使用默认的 PHTREAD_CRATE_JOINABLE),使用
pthread_join()
。You can either suspend the execution of the main process waiting for a signal, or don't detach the thread (using the default PHTREAD_CRATE_JOINABLE) waiting for its termination with a
pthread_join()
.是否有理由不能以相反的方式做事:让主线程运行循环,并在后台线程中执行一次性任务?
Is there a reason you can't do things the other way round: have the main thread run the loop, and do the one-off task in the background thread?
这不是最优雅的设计,但也许您可以在退出之前阻塞主线程:
然后您可以为 SIGINT 和 SIGTERM 安装一个信号处理程序来打破循环。 最简单的方法是:exit(0) :-)。
Not the most elegant design but maybe you could block the main thread before exiting with:
Then you can install a signal handler for SIGINT and SIGTERM that breaks the loop. The easiest way for that is: exit(0) :-).