NAME
pthread_atfork - register fork handlers
SYNOPSIS
int pthread_atfork(void (*prepare)(void),void (*parent)(void),
void (*child)(void));
DESCRIPTION
The order ofcalls to pthread_atfork() is significant. The parentand child fork handlers shall be called in the order in which they wereestablished by calls to pthread_atfork(). The prepare forkhandlers shall be called in the opposite order.
RETURN VALUE
Upon successful completion, pthread_atfork()shall return a value of zero; otherwise, an error number shall be returned toindicate the error.
ERRORS
The pthread_atfork() function shallfail if:
[ENOMEM] -- Insufficient table space existsto record the fork handler addresses.
The pthread_atfork() function shallnot return an error code of [EINTR].
RATIONALE
The expected usage is that the preparehandler acquires all mutex locks and the other two fork handlers release them.
For example, an application can supply a prepareroutine that acquires the necessary mutexes the library maintains and supply childand parent routines that release those mutexes, thus ensuring that thechild gets a consistent snapshot of the state of the library (and that nomutexes are left stranded). Alternatively, some libraries might be able tosupply just a child routine that reinitializes the mutexes in thelibrary and all associated states to some known value (for example, what it waswhen the image was originally executed).
A higher-level package may acquire locks onits own data structures before invoking lower-level packages. Under thisscenario, the order specified for fork handler calls allows a simple rule ofinitialization for avoiding package deadlock: a packageinitializes all packages on which it depends before it calls the pthread_atfork()function for itself.
MY NOTES:
2. The expected usage is thatthe prepare handler acquires all mutex locks and the other two forkhandlers release them.
3. Pay attentionon the order of calls to pthread_atfork() to make sure the low-levelpackage’s prepare handle is calledfirst.
4. Only a shortlist of async-signal-safe library routines are promised to be available for parentand child fork handler.malloc/free(new/delete?), printf and so on are not async-signal-safe!
5. In theory,1) only async-signal-safe can be called in parent and child fork handler; 2) many OS functions havestatic variable, whom status can’t clean up; pthread_atfork()function is still an option to reduce the bug of fork() in multi-threadprogram, especially for LIB.
6. If #4 isobey, some occasional bug can happen.
---------------------------------------------------
歡迎轉載,請注明作者和出處
本文轉自 zhenjing 部落格園部落格,原文連結:http://www.cnblogs.com/zhenjing/archive/2010/12/28/pthread_atfork.html ,如需轉載請自行聯系原作者