0
#include <semaphore.h>

sem_t* x;

int main () 
{
    x = sem_open("x", O_CREAT, 0, 0);;
    sem_wait(x); sem_wait(x); sem_wait(x);
    std::cout << "\ndone\n";
}

This code shouldn't even pass the first sem_wait() but on my system it reaches the end of main(). Everything I have read, such as here and here, say that, although Mac OS X does not support sem_init(), it does support sem_open(). However, using sem_open() as above hasn't fixed the problem. I'm running OS X 10.5.7.

Community
  • 1
  • 1
Matt Munson
  • 2,903
  • 5
  • 33
  • 52

2 Answers2

5

Try putting sem_unlink("x"); before sem_open(), I'm sure it's not your first attempt on it. And mode of 0 won't let you do much with it, unless you remove it. Also, do check your calls for errors, it will if not resolve, but, at least, amend your questions.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
  • `sem_unlink("x");` did the trick. Does this mean that a named semaphore persists after the calling process ends, unless it is explicitly unlinked, thus causing `O_CREAT` to fail due to the semaphore already being present? But actually I still don't quite see how that would account for the behavior. – Matt Munson Nov 09 '11 at 11:13
  • 2
    Yes, it does persist. The problem is not the `O_CREAT` flag, it's supposed to create semaphore if it doesn't exist (unlike `O_EXCL` which supposed to make it fail if it exists). The problem is that semaphore exists and restricts all kind of access (mode of 0). That's why you need to unlink it first. – Michael Krelin - hacker Nov 09 '11 at 11:29
  • Kewl, that's it! Thanks a lot. – lambruscoAcido Apr 18 '21 at 17:01
1

Permissions of 0 to sem_open mean that nobody can access the semaphore. You really should add proper error checking -- it will tell you which function is failing and way.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278