当线程分叉时会发生什么? [英] What happens when a thread forks?

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

问题描述

我知道从线程调用 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;
     }
 }

推荐答案

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

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

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.)

如果其父进程首先完成,则新进程将附加到 init 进程.

If its parent finishes first, the new process will be attached to init process.

如果父母先完成,则向孩子发送一个 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.

它的父线程是主线程,而不是创建它的线程.

And its parent is main thread, not the thread that created it.

一个进程的父进程是一个进程,而不是一个特定的线程,所以说主线程或子线程是父线程是没有意义的.整个过程是父进程.

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆