In order to create a new semaphore set, or access an existing set, the semget() system call is used.
SYSTEM CALL: semget(); PROTOTYPE: int semget ( key_t key, int nsems, int semflg ); RETURNS: semaphore set IPC identifier on success -1 on error: errno = EACCESS (permission denied) EEXIST (set exists, cannot create (IPC_EXCL)) EIDRM (set is marked for deletion) ENOENT (set does not exist, no IPC_CREAT was used) ENOMEM (Not enough memory to create new set) ENOSPC (Maximum set limit exceeded) NOTES:
Create the semaphore set if it doesn't already exist in the kernel.
When used with IPC_CREAT, fail if semaphore set already exists.
If IPC_CREAT is used alone, semget() either returns the semaphore set identifier for a newly created set, or returns the identifier for a set which exists with the same key value. If IPC_EXCL is used along with IPC_CREAT, then either a new set is created, or if the set exists, the call fails with -1. IPC_EXCL is useless by itself, but when combined with IPC_CREAT, it can be used as a facility to guarantee that no existing semaphore set is opened for access.
As with the other forms of System V IPC, an optional octal mode may be OR'd into the mask to form the permissions on the semaphore set.
The nsems argument specifies the number of semaphores that should be created in a new set. This represents the number of printers in our fictional print room described earlier. The maximum number of semaphores in a set is defined in ``linux/sem.h'' as:
#define SEMMSL 32 /* <=512 max num of semaphores per id */
Note that the nsems argument is ignored if you are explicitly opening an existing set.
Let's create a wrapper function for opening or creating semaphore sets:
int open_semaphore_set( key_t keyval, int numsems ) { int sid; if ( ! numsems ) return(-1); if((sid = semget( mykey, numsems, IPC_CREAT | 0660 )) == -1) { return(-1); } return(sid); }