Is it correct to call semget () and then semop () without calling semctl ()?

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.

/*
** initsem() -- more-than-inspired by W. Richard Stevens' UNIX Network
** Programming 2nd edition, volume 2, lockvsem.c, page 295.
*/
int initsem(key_t key, int nsems)  /* key from ftok() */
{
    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) { /* we got it first */
        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++) { 
            /* do a semop() to "free" the semaphores. */
            /* this sets the sem_otime field, as needed below. */
            if (semop(semid, &sb, 1) == -1) {
                int e = errno;
                semctl(semid, 0, IPC_RMID); /* clean up */
                errno = e;
                return -1; /* error, check errno */
            }
        }

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 .

? , , ?

+4
2

, . POSIX.1-2008 semget :

semid_ds, :

  • sem_perm.cuid, sem_perm.uid, sem_perm.cgid sem_perm.gid , , .

  • 9 sem_perm.mode 9 semflg.

  • sem_nsems ​​ nsems.

  • sem_otime ​​ 0 sem_ctime ​​ , IPC .

  • , , . semctl() SETVAL SETALL .

+5

, , ...


( SO). , , , : , , .


, :

. (POSIX.1-2001 POSIX.1-2008 , POSIX.1-2008 , 0.) Linux, , 0, : .

, : " Beej Unix IPC". , :

  • - - . , , "Beej".

  • Unix (Linux , . ).

  • Beej resume (PDF), , , , . tinkerer, , . - , , .

, , , , , //// .. , POSIXey ,

1.1.

C ++ Unix ( POSIXey, ), .

(...)

1.2.

Linux gcc. Unix.

, : , Linux gcc. , :

Hacker IPC Linux GCC

Rusty Russell ! ( , ). , , POSIX?

+2

Source: https://habr.com/ru/post/1660960/


All Articles