本文介绍了线程分叉时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道从线程调用fork() sys_call是一个坏主意.但是,如果线程使用fork()创建新进程会发生什么?

I know calling fork() sys_call from a thread is a bad idea.However, what will happen if a thread creates a new process using fork()?

新进程将是创建线程的主线程的子进程.我想.

The new process will be the child of the main thread that created the thread. I think.

如果其父级先完成,则新进程将附加到init进程中.它的父级是主线程,而不是创建它的线程.

If its parent finishes first, the new process will be attached to init process.And its parent is main thread, not the thread that created it.

如果我做错了,请纠正我.

Correct me if I am wrong.

#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;
     }
 }

推荐答案

fork创建一个新进程.一个进程的父进程是另一个进程,而不是线程.因此,新流程的父级是旧流程.

fork creates a new process. The parent of a process is another process, not a thread. So the parent of the new process is the old process.

请注意,子进程将只有一个线程,因为fork仅复制调用fork的(堆栈)线程. (这并不完全正确:整个内存都是重复的,但是子进程将只有一个活动线程.)

Note that the child process will only have one thread because fork only duplicates the (stack for the) thread that calls fork. (This is not entirely true: the entire memory is duplicated, but the child process will only have one active thread.)

如果父母先完成,则将SIGHUP信号发送给孩子.如果子级由于SIGHUP而没有退出,它将获得init作为其新的父级.有关SIGHUP的更多信息,另请参见nohupsignal(7)的手册页.

If the parent finishes first a SIGHUP signal is sent to the child. If the child does not exit as a result of the SIGHUP it will get init as its new parent. See also the man pages for nohup and signal(7) for a bit more information on SIGHUP.

进程的父级是进程,而不是特定的线程,因此说主线程或子线程是父级是没有意义的.整个过程是父母.

The parent of a process is a process, not a specific thread, so it is not meaningful to say that the main or child thread is the parent. The entire process is the parent.

最后一个注意事项:混合螺纹和前叉时必须格外小心. 此处.

One final note: Mixing threads and fork must be done with care. Some of the pitfalls are discussed here.

这篇关于线程分叉时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 20:57