fork调用后,父进程的线程是否会被子进程继承?


如题。父进程如果有多个线程,是否也被子进程继承。

如果被继承,那么,当父进程有一个线程在执行写独享的文件的时候,怎么处理的呢?

如果没有被继承,那么,由于线程资源也是属于父进程的资源,为什么不继承呢?

操作系统 Linux

狂気DNEET 12 years ago

不可能继承,因为fork后子进程只能有一个线程。道理其实很简单,如果需要继承所有线程,简直是无法想象的。比如,进程A里,线程A_1正在操作一个链表,这时线程A_2正在操作一个栈,而线程A_3fork出了进程B, 难道要让B_1应该在哪里接着运行呢?是操作A_1的链表还是操作A_2的栈?
根据Unix 98标准, 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. [THR]   Fork handlers may be established by means of the pthread_atfork() function in order to maintain application invariants across fork() calls.
  

When the application calls fork() from a signal handler and any of the fork handlers registered by pthread_atfork() calls a function that is not asynch-signal-safe, the behavior is undefined.

游戏X黑魔导 answered 12 years ago

Your Answer