为什么semop(semid,& wait [1],2);在一组三个信号量上减少第0个信号量而不是第1个和第2个信号量的值?

时间:2011-02-20 15:40:23

标签: c linux unix operating-system semaphore

我有一个代码,我正在处理一组3个信号量。我有两套 struct sembuf wait[3],signal[3];

我已经初始化了每一个。 wait初始化为-1,信号初始化为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

1 个答案:

答案 0 :(得分:4)

您在所有参数中使用了sem_num = 0.