fork and pthreads
fork and pthreads
- Subject: fork and pthreads
- From: email@hidden
- Date: Sun, 17 Nov 2013 21:07:10 -0500
Can anyone help me with this following?
The standard idiom for protecting mutexes across fork
is to register atfork handlers which lock the mutex in
the `prepare' handler before the fork, and unlock them
in the post-fork handlers.
The toy program given below follows this convention.
To aid debugging I've used error checking mutexes.
The problem is trying to unlock the mutex in the child,
where the attempt fails with EPERM.
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
static pthread_mutex_t mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER;
static void lock_mutex ( pthread_mutex_t *m )
{
int err = pthread_mutex_lock ( m );
if ( 0 != err )
{
printf ( "error locking mutex: %s\n", sys_errlist [ err ] );
exit ( 1 );
}
} /* lock_mutex */
static void unlock_mutex ( pthread_mutex_t *m, char *id )
{
int err = pthread_mutex_unlock ( m );
if ( 0 != err )
{
printf ( "%s: error locking mutex: %s\n", id, sys_errlist [ err ] );
exit ( 1 );
}
} /* unlock_mutex */
static void atfork_prepare (void)
{
lock_mutex ( &mutex );
} /* atfork_prepare */
static void atfork_post_common ( char *id )
{
unlock_mutex ( &mutex, id );
} /* atfork_post_common */
static void atfork_parent (void)
{
atfork_post_common ( "parent" );
} /* atfork_parent */
static void atfork_child (void)
{
atfork_post_common ( "child" );
} /* atfork_child */
int main ( int argc, char *argv [] )
{
int err;
pid_t pid;
err = pthread_atfork ( atfork_prepare, atfork_parent, atfork_child );
assert ( 0 == err );
pid = fork ();
if ( 0 == pid )
{
printf ( "child\n" );
}
else if ( pid > 0 )
{
printf ( "parent\n" );
}
else
{
perror ( "error forking\n" );
}
return 0;
}
I build like this:
cc -g t_atfork.c -lpthread -o t_atfork
and I see the following output:
i386-darwin% ./t_atfork
parent
child: error unlocking mutex: Operation not permitted
What am I not getting right?
Thanks,
Ariel Burton
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden