# POSIX semaphores



## schiuma (Mar 29, 2013)

Hello all,

I'm a newbie on FreeBSD programming. I'm trying to use the POSIX semaphores to synchronize two processes. The code of my consumer is the following:


```
sem_t *sem = sem_open("/my_sem", O_CREATE|O_RDWR,0644,0);
sem_wait(sem);
```

The code of my producer is the following:


```
sem_t *sem = sem_open("/my_sem", O_RDWR);
sem_post(sem);
```

On Ubuntu Linux this code works fine, while on FreeBSD I get a core dump on the functions sem_wait() and sem_post().

I printed "sem" through 
	
	



```
printf("%p\n",sem)
```
 and I got 0x0. Furthermore, I noticed that the directory /dev/shm does not exist. 

Thank you very much for your help :beer


----------



## fonz (Mar 29, 2013)

schiuma said:
			
		

> ```
> sem_t *sem = sem_open("/my_sem", O_CREATE|O_RDWR,0644,0);
> sem_wait(sem);
> ```


For starters, I highly recommend checking return values. Failure to do so is a frequent cause of (sometimes rather mysterious) crashes (particularly in networking code, but the principle applies generally). For example, use something along the lines of the following:

```
sem_t *sem;

if((sem=sem_open("/my_sem", O_CREATE|O_RDWR,0644,0))==SEM_FAILED)
{
  perror("sem_open()");
  exit(1);
}
```



			
				schiuma said:
			
		

> I printed "sem" through printf("%p\n",sem), and I got 0x0.


That means that sem is a NULL pointer (the value SEM_FAILED is defined in <semaphore.h> as ((sem_t *)0)), so apparently the call to sem_open() failed. If you use something like what I wrote above, what does perror(3) say?


----------



## schiuma (Mar 29, 2013)

> If you use something like what I wrote above, what does perror(3) say?



I get the message


```
sem_open(): Invalid argument
```


----------



## kpa (Mar 29, 2013)

I bet it's trying to open the semaphore literally as  /my_sem, does the process have priviledges to create files under / ?


----------



## schiuma (Mar 29, 2013)

Yes, I'm running the process as root.


----------



## Anonymous (Mar 29, 2013)

According to sem_open(3)(), the bit O_RDWR is not in the list of bits that _"may be set in the oflag argument"_. So, perhaps ...|O_RDWR constitutes for the _"invalid argument"_.


----------



## schiuma (Mar 29, 2013)

You're right! O_RDWR exists only on Linux. Thank you very much!


----------



## fonz (Mar 29, 2013)

schiuma said:
			
		

> O_RDWR exists only on Linux[red].[/red]


Yeah, even though it's all (supposed to be, anyway) POSIX sometimes there are these rather subtle incompatibilities between Linux and (Free)BSD. I remember when working with POSIX threads (pthread(3)) that I used some kind of flag that was available on FreeBSD but not on Linux. Fooled a computer science PhD with that one, go figure


----------

