C - 在多线程进程中 exec 是否必须立即跟随 fork ?
情况: 我有一个用 C 编写的多线程程序。如果其中一个线程分叉,则使用 exec() 将子进程替换为另一个线程,并且父进程等待子进程退出。
问题: 通过 fork() 创建子进程后,有几行代码编译要在以下 exec() 命令中使用的参数。
假设 我是否正确地假设在 fork() 创建子进程和被 exec() 替换子进程之间的时间里,子进程(作为父进程的副本)将拥有父进程的所有线程,因此这些线程会运行——尽管持续时间很短?
如果是这样,在 fork() 之后立即调用 exec() 是正确的解决方案吗?
Situation:
I have a multithreaded program written in C. If one of the threads forks, the child process is replaced by another using exec() and the parent waits for the child to exit.
Problem:
After the child process is created by fork() there are a few lines of code that compile the arguments to be used in the following exec() command.
Hypothesis
Am I correct in assuming that in the time between the child process being created by fork() and being replaced by exec(), the child process - being a copy of the parent - will have all the threads of the parent and therefore these threads will run - albeit for a very brief period?
If so, is the correct solution to call exec() immediately after fork()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只有调用
fork
的线程才会在新进程中运行。但是,在exec
之前可以调用的函数是有限制的。来自fork
:我相信这意味着你通常应该没问题,只要任何多线程
库正确使用
pthread_atfork
。编辑:
pthread_atfork
页面进一步解释了如何图书馆可以保护自己:Only the thread that calls
fork
will be running in the new process. However, there are limits to which functions you can call beforeexec
. Fromfork
:I believe this means you should generally be okay, as long as any multi-threaded
libraries use
pthread_atfork
properly.EDIT: The
pthread_atfork
page explains further how the library can protect itself:正如 @Matthew 在他的回答中所写,父进程中的其他线程将不会存在于子进程中(如果您使用的是 PThreads)。
请注意,如果不是这样,那么将 exec() 调用“紧接在”fork 调用之后是无济于事的,因为其他线程仍然有可能在调用 exec() 之前运行。但是,您可以通过在调用 fork() 之前锁定互斥体来控制这一点 - 它实际上会被调用 exec() 破坏。
As @Matthew wrote in his answer, the other threads from the parent process will not exist in the child process (if you are using PThreads).
Note that if this were not so, it wouldn't help to place the exec() call "immediately after" the call to fork, since there would still be the possibility that the other threads would run before the call to exec(). You could, however, control this by locking a mutex before calling fork() - it would essentially get destroyed by the call to exec().
我也认为,所有线程也将在子进程中复制。但事实并非如此。由于其他线程不会在子进程中复制,因此如果您在 exec 之前使用互斥体/锁,则需要确保编写 fork 处理程序以正确处理它们。
这是一篇关于它的文章。
http://learnwithtechies.com/tech/index.php?option=com_content&view=article&id=15:fork-in-multithreaded-environment&catid=10:unix
I too thought , all the threads will be replicated in the child process too. But thats not true. Since other threads are not replicated in the child process, if you are using mutexes/locks before exec, you need to make sure that fork handlers are written to handle them properly.
Here is an article on it.
http://learnwithtechies.com/tech/index.php?option=com_content&view=article&id=15:fork-in-multithreaded-environment&catid=10:unix