How to make C++ code fork-safe?
- From: Arkadiy <vertleyb@xxxxxxxxx>
- Date: Fri, 30 Nov 2007 11:26:26 -0800 (PST)
Hi all.
I've been programming in C++ for quite some time, but I am new in the
unix world. One thing that keeps surprizing me is fork()...
The software I am working on right now seems to use fork() quite
extensively. Besides the fact that it runs under Apache (which forks,
I think, in rather controlled manner), forks are used left and right
in the module itself. It seems that, when something needs to be done
asynchronously, a fork() is issued, the work is done in the child
process, and then the child is terminated.
First issue I ran into was a thread created in the singleton
constructor not replicated in the forked process. This was quite easy
to workaround once I figured what's happenning, but then it became
worse... The condition variable inited in parent process hanged in
pthread_cond_destroy() at the child process termination. Then we
found pthread_atexit...
Now I think I ran into another related issue. I will not describe it
here, but rather try to provide some generic description:
Supposedly you have a global object (singleton, etc.). To make it
thread-safe you lock some of its operations. In the middle of such
operation the object may be in an inconsistent state. Let's say a
fork is issued from another thread during such an operation (most
likely the thread calling fork() does not lock your global object).
It copies the object into the child process while it is in the middle
of something... Later on it crashes in the destructor when the child
is terminated.
Even better, recall the problem with the double-check pattern
(described in http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf).
Looks like this problem directly applies to fork() if it is issued
from another thread after the pointer is assigned but before the
object is initialized.
Now I am wondering if there exist any rules that can be applied to
make your C++ code fork-safe? Or does the usage of fork() itself
needs to be limited?
Thanks for any advice.
Arkadiy
.
- Prev by Date: Re: C/C++ on UNIX Developer required in Woodmead, Johannesburg
- Next by Date: Re: pthread_cond_timedwait and signal handler
- Previous by thread: C/C++ on UNIX Developer required in Woodmead, Johannesburg
- Index(es):
Relevant Pages
|
|