我知道从线程调用 fork() sys_call
是个坏主意。
但是,如果一个线程使用 fork()
创建一个新进程会发生什么?
新进程将是创建该线程的主线程的子进程。我想。
如果其父进程先完成,则新进程将附加到 init 进程。 它的父线程是主线程,而不是创建它的线程。
如果我错了,请纠正我。
#include <stdio.h>
#include <pthread.h>
int main ()
{
thread_t pid;
pthread_create(&(pid), NULL, &(f),NULL);
pthread_join(tid, NULL);
return 0;
}
void* f()
{
int i;
i = fork();
if (i < 0) {
// handle error
} else if (i == 0) // son process
{
// Do something;
} else {
// Do something;
}
}
最佳答案
The new process will be the child of the main thread that created the thread. I think.
fork
创建一个新进程。进程的父进程是另一个进程,而不是线程。所以新进程的父进程是旧进程。
请注意,子进程将只有一个线程,因为 fork
只会复制调用 fork
的线程(堆栈)。 (这并不完全正确:整个内存被复制,但子进程将只有一个事件线程。)
If its parent finishes first, the new process will be attached to init process.
如果父进程先完成,一个SIGHUP
信号被发送给子进程。如果子进程没有因为 SIGHUP
而退出,它将获得 init
作为它的新父进程。有关 SIGHUP
的更多信息,另请参阅 nohup
和 signal(7)
的手册页。
And its parent is main thread, not the thread that created it.
进程的父进程是进程,而不是具体的线程,所以说主线程或子线程是父进程是没有意义的。整个过程都是父进程。
最后一点:必须小心混合线程和 fork 。讨论了一些陷阱 here .
关于c - 当线程 fork 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39890363/