View Full Version : What is wrong with this function?

01-08-2007, 03:10 PM
Ok, i have this function and for some reason the return value is ...........

sem_t *semn_open(int id){
return (sem_t*)sem_open("/999", O_CREAT);

Obviously this is a simplified version of the function... but it doesn't work anyway!

I'm calling this with:

sem_t *temp;
// causes segmentation fault
temp = semn_open(999);
// all OK
// temp = sem_open("/999", O_CREAT);

Can anyone help me?

Thanks in advance

01-08-2007, 03:36 PM
Yeah, too simplified to make any sense out of it.

Post an actual example which fails, not random single lines which you think might be the problem.

What is the pointless cast on
return (sem_t*)sem_open("/999", O_CREAT);

01-08-2007, 05:47 PM
OK sorry!

Here is a fully functional code. Surprisingly I noticed that the problem doesn't come from my_sem_open but from sem_open itself (?!)

I don't get any errors but the output is "* test * test * test * test ...."

#include <stdio.h>
#include <fcntl.h>
#include <semaphore.h>

sem_t *my_sem_open() {
return sem_open("/100", O_CREAT);

int main() {
sem_t *temp;
if ((temp = sem_open("/100", O_CREAT)) == (void*)-1) {
return 0;
printf("going to wait..\n");
for (;;) {
printf("* test ");
return 0;

01-08-2007, 07:33 PM
Heh - I get a segfault

01-09-2007, 06:11 AM
Apparently, you need to read the manual

O_CREAT This flag is used to create a semaphore if it does not
already exist. The O_CREAT argument requires additional
arguments: mode of type mode_t, and value of type unsigned
int. After the semaphore is created, other processes can
open the semaphore by calling sem_open with the same value
for the name argument.

If you don't supply the required arguments, it just uses whatever random junk is on the stack, and thus leads to chaotic behaviour depending on how you arrange the code.

01-10-2007, 05:18 PM

Got it! Thanks! :)