The standard idiom for using pthread_atfork supposed to be to get all the locks in the pre-fork handler and release them in both the parent and the child handlers. However, as far as I can tell, this is not possible. pthread_mutex_unlock specified either for undefined behavior (in the case of normal, or for mutexes of the default type), or for failure (in the case of recursive or bypass mutexes) if the calling thread is not the owner of the mutex. And in the child handler registered with pthread_atfork , the calling thread is the main thread of the newly created process and, therefore, cannot be the owner of the mutex.
Am I mistaken or the whole idiom pthread_atfork , broken by design and almost impossible to use?
Edit: I also don't see any valid (portable) workaround for the problem. Ideally, you can simply destroy and reinitialize the mutexes in the child process, except that the pthread_mutex_destroy call in the initialized mutex is defined as undefined behavior to accommodate funny implementations in which the mutexes are not PODs but contain a reference to some kernel-level object.
source share