Help Needed 101
Help Needed 101

Reputation: 139

Semaphores System V - semop implementation

As you can see in the semaphore System V documentation (http://man7.org/linux/man-pages/man2/semop.2.html) there is a part that states the following:

EXAMPLE

The following code segment uses semop() to atomically wait for the value of semaphore 0 to become zero, and then increment the semaphore value by one.

      struct sembuf sops[2];
       int semid;

      /* Code to set semid omitted */

      sops[0].sem_num = 0;        /* Operate on semaphore 0 */
      sops[0].sem_op = 0;         /* Wait for value to equal 0 */
      sops[0].sem_flg = 0;

      sops[1].sem_num = 0;        /* Operate on semaphore 0 */
      sops[1].sem_op = 1;         /* Increment value by one */
      sops[1].sem_flg = 0;

      if (semop(semid, sops, 2) == -1) {
          perror("semop");
          exit(EXIT_FAILURE);
      }

After this example I have several questions:

1- Does (semop(semid, sops, 2) == -1) executes the 2 sops positions? sops[0] and sops[1]?

2- If so why does sops[0].sem_op = 0; Waits for value of the semid to equal 0?

Upvotes: 0

Views: 1531

Answers (1)

John Bollinger
John Bollinger

Reputation: 181459

1- Does (semop(semid, sops, 2) == -1) executes the 2 sops positions? sops[0] and sops[1]?

It attempts to do so, yes. That's what the semop() function does, and it has to run in order to return a value (which the example code then tests against -1). Like many C functions, semop() returns -1 when it fails; in that case, for that function, you can rely on neither operation having been performed. Otherwise, semop() returns 0, and in that case you can rely on both operations having been performed.

2- If so why does sops[0].sem_op = 0; Waits for value of the semid to equal 0?

Because that's what that value of the sem_op is defined to mean. As the documentation that you yourself linked puts it:

If sem_op is zero, the process must have read permission on the semaphore set. This is a "wait-for-zero" operation [...]

Upvotes: 1

Related Questions