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
- The name identifies the semaphore.
- 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
- 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
- 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.
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.
In the next article, we will look at an unnamed Semaphore requirements
Pingback: Locking Mechanisms for Threads | Hitch Hiker's Guide to Learning