信号量系统 V - semop 实现
Semaphores System V - semop implementation
正如您在信号量系统 V 文档 (http://man7.org/linux/man-pages/man2/semop.2.html) 中看到的那样,有一部分内容如下:
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);
}
在这个例子之后我有几个问题:
1- (semop(semid, sops, 2) == -1)
是否执行 2 个 sop 位置? sops[0] 和 sops[1]?
2- 如果是这样,为什么 sops[0].sem_op = 0;
等待 semid 的值等于 0?
1- Does (semop(semid, sops, 2) == -1) executes the 2 sops positions? sops[0] and sops[1]?
它试图这样做,是的。这就是 semop()
函数 所做的 ,它必须 运行 才能 return 一个值(然后示例代码针对 -1 进行测试).像许多 C 函数一样,semop()
returns -1 当它失败时;在这种情况下,对于该功能,您可以相信这两个操作都没有执行。否则,semop()
returns 0,在这种情况下,您可以相信这两个操作都已执行。
2- If so why does sops[0].sem_op = 0; Waits for value of the semid to equal 0?
因为 sem_op
的值就是这个意思。正如您自己链接的文档所说:
If sem_op
is zero, the process must have read permission on the
semaphore set. This is a "wait-for-zero" operation [...]
正如您在信号量系统 V 文档 (http://man7.org/linux/man-pages/man2/semop.2.html) 中看到的那样,有一部分内容如下:
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); }
在这个例子之后我有几个问题:
1- (semop(semid, sops, 2) == -1)
是否执行 2 个 sop 位置? sops[0] 和 sops[1]?
2- 如果是这样,为什么 sops[0].sem_op = 0;
等待 semid 的值等于 0?
1- Does (semop(semid, sops, 2) == -1) executes the 2 sops positions? sops[0] and sops[1]?
它试图这样做,是的。这就是 semop()
函数 所做的 ,它必须 运行 才能 return 一个值(然后示例代码针对 -1 进行测试).像许多 C 函数一样,semop()
returns -1 当它失败时;在这种情况下,对于该功能,您可以相信这两个操作都没有执行。否则,semop()
returns 0,在这种情况下,您可以相信这两个操作都已执行。
2- If so why does sops[0].sem_op = 0; Waits for value of the semid to equal 0?
因为 sem_op
的值就是这个意思。正如您自己链接的文档所说:
If
sem_op
is zero, the process must have read permission on the semaphore set. This is a "wait-for-zero" operation [...]