Process shared mutex

I have a scenario where i need a process shared mutex.So i modified the example given for shm_open() from neutrino lib reference.But the below code fails at pthread_mutex_init() with EFAULT.Can someone help me with this?

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <sys/mman.h>
#include <pthread.h>
main()
{
/* Create a new memory object */

int fd;
pthread_mutex_t *addr;
pthread_mutexattr_t muAttr;
int status;
void * addr1;

fd = shm_open( “/bolts”, O_RDWR | O_CREAT | O_EXCL, 0777 );

if( fd == -1 )
{
fprintf( stderr, “Open failed:%s\n”,
strerror( errno ) );

printf("Removing bolts");
shm_unlink( "/bolts" );
return EXIT_FAILURE;

}

if( ftruncate( fd, sizeof(pthread_mutex_t) == -1 ))
{
fprintf( stderr, “ftruncate: %s\n”,
strerror( errno ) );
return EXIT_FAILURE;
}

addr1 = mmap( 0, sizeof(pthread_mutex_t),
PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0 );

if( addr1 == MAP_FAILED ) {
fprintf( stderr, “mmap failed: %s\n”,
strerror( errno ) );
return EXIT_FAILURE;
}

addr = (pthread_mutex_t*)addr1;

if (pthread_mutexattr_init(&muAttr) != EOK)
{
printf(“Mutex attr init failed\n”);
return EXIT_FAILURE;
}

if (pthread_mutexattr_setpshared(&muAttr,PTHREAD_PROCESS_SHARED) != EOK)
{
printf(“Mutex sharing failed\n”);
return EXIT_FAILURE;
}

if ((status = pthread_mutex_init(addr,&muAttr)) != EOK)
{
printf(“Mutex init failed with status = %d”,status);
return EXIT_FAILURE;
}

pthread_mutex_lock(addr);

printf(“Process1 acquired lock”);

sleep(20);

pthread_mutex_unlock(addr);

}

Vjay,

You have a very simple but insidious error here:

This line:

if( ftruncate( fd, sizeof(pthread_mutex_t) == -1 ))

has the brackets in the wrong place so that you end up truncating at 0 size. Once I changed it to:

if( ftruncate( fd, sizeof(pthread_mutex_t)) == -1 )

it worked fine.

Tim

Thanks tim.I did see that shared memory i created had zero bytes but i could not zero it on ftruncate.This is y i hate c language so much.Thanks once again tim.

You didn’t compile with warning on as you would have discovered your declaration of main is non-standard and not returning any value at the end.

As for the error in ftruncate, a tool such as pclint/lint would have caught this no sweet. I’m a BIG fan of this tool. It usually pay for itself within 15 minutes ;-) I have yet to find a project lint didn’t find a bug in.