我有一个代码,我正在处理一组3个信号量。我有两套
struct sembuf wait[3],signal[3];
我已经初始化了每一个。wait初始化为-1,signal初始化为1
然后,我使用成功工作的函数semctl(semid,0,SETALL,2);将它们的值设置为2。然后我检查它们的值是否已设置,它们是否已设置。
然后我会semop(semid,&wait[1],2);。这应该在两个信号量上等待并减少它们的值。所以我希望此时三个信号量的值是2,1,1,但令我惊讶的是,它两次减少了第一个信号量的值,我看到的值是0,2,2。
有人能告诉我为什么会这样吗?
这是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<sys/sem.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>

int main(int argc,char *argv[]){

    key_t key1 = 12345;
    int semid;
    unsigned short *semval;

    struct sembuf wait[3],signal[3];
    semval = (unsigned short*) malloc(sizeof(unsigned short) * 3);

    wait[0].sem_num = 0;
    wait[0].sem_op = -1;
    wait[0].sem_flg = SEM_UNDO;

    signal[0].sem_num = 0;
    signal[0].sem_op = 1;
    signal[0].sem_flg = SEM_UNDO;

    wait[1].sem_num = 0;
    wait[1].sem_op = -1;
    wait[1].sem_flg = SEM_UNDO;

    signal[1].sem_num = 0;
    signal[1].sem_op = 1;
    signal[1].sem_flg = SEM_UNDO;

    wait[2].sem_num = 0;
    wait[2].sem_op = -1;
    wait[2].sem_flg = SEM_UNDO;

    signal[2].sem_num = 0;
    signal[2].sem_op = 1;
    signal[2].sem_flg = SEM_UNDO;

    semid = semget(key1,3,IPC_CREAT);
    printf("ALLOCATING THE SEMAPHORES = %s\n",strerror(errno));

    semval[0] = semval[1] = semval[2] = 2;
    semctl(semid,0,SETALL,semval);
    printf("SETTING SEMAPHORE VALUES = %s\n",strerror(errno));

    semctl(semid,0,GETALL,semval);
    printf("Initialized Semaphore values : %d--%d--%d\n",semval[0],semval[1],semval[2]);

    semop(semid,&wait[1],2);
    printf("WAITING ON SEMAPHORES 2 AND 3 = %s\n",strerror(errno));

    semctl(semid,0,GETALL,semval);
    printf("VALUES AFTER WAITING ON SEMAPHORES 2 AND 3 : %d--%d--%d\n",semval[0],semval[1],semval[2]);

    semctl(semid,0,IPC_RMID);
    printf("SEMAPHORE REMOVED = %s\n",strerror(errno));
    return 0;
}

这里是输出
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ gcc -g -o sem3 sem3.c
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ sudo ./sem3
ALLOCATING THE SEMAPHORES = Success
SETTING SEMAPHORE VALUES = Success
Initialized Semaphore values : 2--2--2
WAITING ON SEMAPHORES 2 AND 3 = Success
VALUES AFTER WAITING ON SEMAPHORES 2 AND 3 : 0--2--2
SEMAPHORE REMOVED = Success

终于在上面写了个博客。
http://systemsdaemon.blogspot.com/2011/02/system-v-semaphores-for-babies.html

最佳答案

在所有参数中都使用了sem_num=0。

关于c - 为什么semop(semid,&wait [1],2);在一组三个信号量上是否减少了第0个信号量而不是第一个和第二个信号量的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5058022/

10-13 08:59