1

I already read the following 2 posts:

But both don't really help me understanding how to make proper use of the semaphores in Linux.

What I want to achieve is e.g. finding out if the current process is the last process having a file open or how many processes have a certain shared object in memory right now from within that very same shared object.

I thought a named Semaphore would be the way to go and on Windows this works like a charm. On Linux however I am facing the challenge of knowing the proper moment to call sem_unlink which is discussed in the first link from above. I understood the behaviour but I would still argue the function is rather unusable for my scenario. Since I don't know when certain processes loading my library are being started it might happen that after a process has terminated another one starts and this one again shall use the very same lock, thus I cannot call sem_unlink when the first process dies (assuming at least one more continues to execute). I can neither call sem_unlink when the last process dies since I never know which one is the last.

This comes from the fact that sem_getvalue and sem_post are 2 separate functions and therefore not an atomic operation like ReleaseSemaphore on Windows. Therefore when sem_getvalue tells me that there are no more usages this information might be outdated/incorrect already once I call sem_unlink then...

Am I missing something? Or maybe this can even be done without a semaphore?

StefanB
  • 21
  • 4
  • 2
    You want to destroy the semaphore when you destroy the resource it protects. If the resource is persistent, so is the semaphore. Just don't unlink it. – n. m. could be an AI Oct 21 '21 at 14:39
  • Thanks! Thing is I don't really get what happens with the counter of the Semaphore in that case but I guess I need to do some experiments to find out if it is properly decremented/incremented e.g. if a process crashes while holding it. But when thinking about this is doesn't really seem to relate to the sem_unlink call... – StefanB Oct 25 '21 at 06:17

0 Answers0