# posix memory based semaphore in shared memory



## renzor (Jan 23, 2011)

hey folks,

i was trying to use memory based semaphores in shared memory to do some kind of synchronization between two (or more) processes when i ran into a core dump. 

I simplified my program where one process does this (create the shm and initialize the semaphore):

```
// this is a header file used by both progs
typedef struct {
  int cnt;
  sem_t mutex;
} shmd;
```


```
shmd *ptr;
size = sizeof(shmd);

fd = shm_open(path, O_CREAT | O_RDWR, mode);
ftruncate(fd, size);
ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

sem_init(&ptr->mutex, 1, 1); // pshared = 1, value = 1
```

things are fine till here, i can use &ptr->mutex in sem_*() calls.

and the other process does this:

```
shmd *ptr;
size = sizeof(shmd);

fd = shm_open(path, O_RDWR, mode);
ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
```

here if i try to use &ptr->mutex in any of sem_*() calls i get EINVAL (invalid semaphore)

am i doing anything wrong here ?


----------



## jilles@ (Jan 23, 2011)

FreeBSD 8.x and earlier do not support process-shared semaphores in shared memory (as documented in sem_init(3)). FreeBSD 9-current supports this.

In 8.x you can use process-shared semaphores via sem_open() although every operation on the semaphore will be a system call and it is another named object. If those downsides are really important to you, you may consider using the umtx system calls directly.


----------



## renzor (Jan 24, 2011)

jilles@ said:
			
		

> FreeBSD 8.x and earlier do not support process-shared semaphores in shared memory (as documented in sem_init(3)). FreeBSD 9-current supports this.



aah, i think i hurried through the man page and missed this part. Thanks a lot. But the man page says that errno would be set to EPERM if an attempt to create a process-shared semaphore is made. But i don't seem to see behavior.



			
				jilles@ said:
			
		

> In 8.x you can use process-shared semaphores via sem_open() although every operation on the semaphore will be a system call and it is another named object. If those downsides are really important to you, you may consider using the umtx system calls directly.



i can live with sem_open() for now, but will explore on umtx syscalls. Thanks.


----------

