ptg10805159
580 Interprocess Communication Chapter 15
creation mask (Sections 4.5 and 4.8). Note, however,that only read and write access
matter,but the interfaces don’t allow us to specify the mode when we open an existing
semaphore. Implementations usually open semaphores for both reading and writing.
Thevalueargument is used to specify the initial value for the semaphorewhen we
create it. It can take on any value from 0 toSEM_VALUE_MAX(Figure2.9).
If we want to ensurethat we arecreating the semaphore, we can set theoflag
argument toO_CREAT|O_EXCL.This will causesem_opento fail if the semaphore
already exists.
To promote portability, we must follow certain conventions when selecting a
semaphorename.
•The first character in the name should be a slash (/). Although there is no
requirement that an implementation of POSIX semaphores uses the file system,
if the file systemisused, we want to remove any ambiguity as to the starting
point from which the name is interpreted.
•The name should contain no other slashes to avoid implementation-defined
behavior.For example, if the file system is used, the names /mysem and
//mysem would evaluate to the same filename, but if the implementation
doesn’t use the file system, the two names could be treated as different (consider
what would happen if the implementation hashed the name to an integer value
used to identify the semaphore).
•The maximum length of the semaphorename is implementation defined. The
name should be no longer than _POSIX_NAME_MAX(Figure2.8) characters,
because this is the minimum acceptable limit to the maximum name length if the
implementation does use the file system.
Thesem_openfunction returns a semaphorepointer that we can pass to other
semaphorefunctions when we want to operate on the semaphore. When we aredone
with the semaphore, we can call thesem_closefunction to release any resources
associated with the semaphore.
#include <semaphore.h>
int sem_close(sem_t *sem);
Returns: 0 if OK,−1 on error
If our process exits without having first calledsem_close,the kernel will close any
open semaphores automatically.Note that this doesn’t affect the state of the semaphore
value — if we have incremented its value, this doesn’t change just because we exit.
Similarly, if we callsem_close,the semaphorevalue is unaffected. There is no
mechanism equivalent to theSEM_UNDOflag found with XSI semaphores.
To destroy a named semaphore, we can use thesem_unlinkfunction.
#include <semaphore.h>
int sem_unlink(const char *name);
Returns: 0 if OK,−1 on error