Search code examples
forkstatic-librariesdeadlock

How to safely fork() a multi-threaded process?


My program depends on a 3rd party static library. The library will start a thread triggered by the initialization of a global variable and the thread will lock on a mutex, and I can't change the 3rd party's code. In my program inside main(), I will invoke fork() and exit to make my program a daemon.

The behavior described above may result in dead lock because the lock can't get unlocked in the child process forked when the global variable is being uninitialized after main().

So now what I want to do is to fork the process before the 3rd party static library is loaded. So is there a proper way to achieve this?


Solution

  • So now what I want to do is to fork the process before the 3rd party static library is loaded. So is there a proper way to achieve this?

    "Before the static library is loaded" is not a thing, static libraries are linked in at build time, not loaded dynamically at runtime.

    The library will start a thread triggered by the initialization of a global variable

    You should consider using a better-designed library, or work with the maintainer to come up with a better-thought-out initialization scheme. Life before main is usually a bad idea. Spawning threads before main is a really bad idea. Alternatives might be, use a lazy static that gets triggered whenever an API of the library is called, or better yet, introducing an explicit init function, or using context pointers so that the user can manage library state. Sorry, it sounds like this thing is a tire fire and theres no sane way to fork it until you invest some time in fixing it.