Named Semaphore in Linux user space

Named semaphores as the name suggests have a name in the Linux file system. Hence different unrelated processes or threads can open the semaphore by invoking the name.

The Named semaphore can be created or an existing instance opened by invoking the “sem_open” API. The API is shown below

FIG Courtesy: Linux Programming Interface
  1. The name identifies the semaphore.
  2. The “oflag” parameter determines if the semaphore already exists or a new semaphore is being created. If the value passed to “oflag” is 0 – the semaphore already exists. If the value is “O_CREAT”, a new semaphore is being created
  3. mode parameter is an optional parameter. it is not present if “oflag” is zero. “mode” parameter is passed when creating a new semaphore. it defines the permissions to be provided for the new semaphore
  4. The “value” parameter – sets an initial value to be assigned to the semaphore.

To close a semaphore created using “sem_open”, “sem_close” can be used. But, closing a semaphore does not delete it from the file system as it has persistence. To remove it from the file system “sem_unlink” API is used which removes all instances of the semaphore to be removed once the processes using it have released it.

FIG Courtesy: Linux Programming Interface

To decrement the value of the semaphore, “sem_wait” API is used. To increment the value and release the semaphore used, “sem_post” API is used.

FIG Courtesy: Linux Programming Interface

In the next article, we will look at an unnamed Semaphore requirements

Unnamed Semaphore in Linux User space

Comments

  1. Pingback: Locking Mechanisms for Threads | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *