I was looking at an example semaphore program in the Beej Guide for Unix IPC .
The sample program contains the following semaphore initialization code. I just post a snippet from it that is relevant to the question. To view the full code, follow the link above.
int initsem(key_t key, int nsems)
{
int i;
union semun arg;
struct semid_ds buf;
struct sembuf sb;
int semid;
semid = semget(key, nsems, IPC_CREAT | IPC_EXCL | 0666);
if (semid >= 0) {
sb.sem_op = 1; sb.sem_flg = 0;
arg.val = 1;
printf("press return\n"); getchar();
for(sb.sem_num = 0; sb.sem_num < nsems; sb.sem_num++) {
if (semop(semid, &sb, 1) == -1) {
int e = errno;
semctl(semid, 0, IPC_RMID);
errno = e;
return -1;
}
}
This is what I can’t understand. As soon as it semget()creates semaphores and successfully returns with a valid semaphore identifier, the semaphores themselves are uninitialized and are in an undefined state. This is confirmed by the man page semget.
Semaphore initialization
. (POSIX.1-2001 POSIX.1-2008 , POSIX.1-2008 , 0.) Linux, , 0, : it .
semctl (2) SETVAL SETALL. , , , sem_otime , semctl (2) IPC_STAT, .
semctl() . semop() sem_op= 1, man- semop .
sem_op - , (semval). , SEM_UNDO, sem_op (semadj) . - . .
semval . 1 .
? , , ?