在多线程进程上调用 fork

Calling fork on a multithreaded process

我对在多线程进程上使用 fork 有疑问。 如果一个进程有多个线程(已经使用 pthread_create 创建并执行了 pthread_join)并且我调用了 fork,它会复制分配给子进程中线程的相同函数还是创建一个 space 我们可以在哪里重新分配功能?

仔细阅读 POSIX 关于 fork() 和线程的内容。特别是:

  • A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called.

子进程在调用线程的上下文中将有一个线程 运行。原始进程的其他部分可能会被不再存在的线程占用(例如,互斥体可能会被锁定)。

基本原理部分(链接页面下方)说:

There are two reasons why POSIX programmers call fork(). One reason is to create a new thread of control within the same program (which was originally only possible in POSIX by creating a new process); the other is to create a new process running a different program. In the latter case, the call to fork() is soon followed by a call to one of the exec functions.

The general problem with making fork() work in a multi-threaded world is what to do with all of the threads. There are two alternatives. One is to copy all of the threads into the new process. This causes the programmer or implementation to deal with threads that are suspended on system calls or that might be about to execute system calls that should not be executed in the new process. The other alternative is to copy only the thread that calls fork(). This creates the difficulty that the state of process-local resources is usually held in process memory. If a thread that is not calling fork() holds a resource, that resource is never released in the child process because the thread whose job it is to release the resource does not exist in the child process.

When a programmer is writing a multi-threaded program, the first described use of fork(), creating new threads in the same program, is provided by the pthread_create() function. The fork() function is thus used only to run new programs, and the effects of calling functions that require certain resources between the call to fork() and the call to an exec function are undefined.