Use pthread_atfork() to prevent deadlocks whenever you use the fork-one model.
#include <pthread.h> int pthread_atfork(void (*prepare) (void), void (* parent) (void), void (*child) (void) );
The pthread_atfork() function declares fork() handlers that are called before and after fork() in the context of the thread that called fork().
The prepare handler is called before fork() starts.
The parent handler is called after fork() returns in the parent.
The child handler is called after fork() returns in the child.
Any handler argument can be set to NULL. The order in which successive calls to pthread_atfork() are made is significant.
For example, a prepare handler could acquire all the mutexes needed. Then the parent and child handlers could release the mutexes. The prepare handler acquiring all required mutexes ensures that all relevant locks are held by the thread calling the fork function before the process is forked. This technique prevents a deadlock in the child.
See the pthread_atfork(3C) man page for more information.