0

I have a semaphore that I tried to change the value of and it fails. After reading the man page I learned that if the value is less than 0 and you use SETVAL it will fail (I wasn't initializing it). But when I initialize it I get "identifier removed" when I call perror(). I am not sure if it is referring to the SETALL or the union.

My initialization looks like this:

union semun argument; 
unsigned short values[1]; 
values[0] = 1; 
argument.array = values; 
int retVal;

//INITIALIZE our semaphore
if(retVal = semctl(semId, 0, SETALL, argument) == -1)
{
    perror("semaphore INITIALIZATION failed\n");
    exit(1);
}

I have my union declared just like the man page and several other websites do and I have a check after semget() to make sure it returns a semaphore so I know that part is working correctly. If anyone could tell me where I am going wrong I would greatly appreciate it.

Also if anyone could please explain the reason behind my error so that I can learn from my mistake that would be most helpful.

Thanks

UPDATE: apparently it did not like the == -1 so I changed it to < 0 and it worked fine really weird I dunno thanks for all the responses though

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
cpowel2
  • 605
  • 1
  • 11
  • 20
  • 2
    Is there a reason you want/need SysV semaphores? POSIX semaphores are generally much nicer (saner API, and much faster since they can be implemented in userspace) but not quite as powerful and might not be available on really old systems. – R.. GitHub STOP HELPING ICE Mar 03 '12 at 02:02
  • When and how did you set `semId`? – alk Mar 03 '12 at 09:09

1 Answers1

2

Probably you missed to initialize semId prior to the call to semctl().

Try to add the folliwing:

int semId = -1;

...

semId = semget(IPC_PRIVATE, 1, IPC_CREAT);
if (-1 == semId)
   perror("semget() failed");
else {
/* Your call to semctl() */
}
alk
  • 69,737
  • 10
  • 105
  • 255