Are all re-entry functions saved after using fork () in a multi-threaded (with pthreads) process?

I am working on a C ++ project that uses pthreads for multithreading, but should also fork from time to time. I read the warnings scattered in the code that memory allocation should never be done after fork , but I did not know exactly why before I found this article . I summed up:

  • When the main thread is fork s, other threads may be in the middle of a library function call; fork ing does not copy other threads, causing calls to become stuck forever;

  • malloc uses a global variable and uses locks to ensure thread safety. Therefore, if one of the threads of the parent process is in the middle in the malloc call, the fork ed child process effectively calls the malloc call forever, which can never recover. The same goes for printf , etc.

I realized that this has something to do with reentrancy , a term that is not mentioned in the article. The requirement seems to be equivalent to:

  • If you call some non-input function f from the main thread in the parent process, the child process cannot call f .

  • malloc not reentrant.

Is this correct, which means that all return functions can be safely used after fork ing? Or am I still missing some unpleasant angles of interaction between pthreads and the traditional UNIX model?

If I'm right, another question arises: malloc , as you know, is not reentrant, but what about C ++ new ? I searched Google for this with few relevant results (mainly due to the difficulty of getting into the correct β€œnew” :), but there is at least one statement that new reentrant . There is also a related question regarding the entire C ++ standard library without a satisfactory answer.

PS. For the interested project, C ++ is the shell of the fish . A plug is definitely needed for shells, and threads are used to improve responsiveness.

+1
unix pthreads fork
source share
1 answer

As @cnicutar noted, the article mentioned that after forking, you can call functions with asynchronous security. And according to this article , reentrant functions are always without asynchronous (but not vice versa), therefore it is safe to call after forking.

This concludes my main question. I will ask an additional question in another thread (pun intended).

Updated: I asked an additional question here .

+2
source share

All Articles