使用 SysV 信号量时不一致

Inconsistency when using SysV semaphores

我正在尝试使用 SysV 信号量和共享内存 API 应用我的信号量理论知识。

简而言之,我在 50 个进程之间共享一个 int 大小的内存(由信号量保护),每个进程将其递增 1000 次,因此最终我的最终值必须为 1000 * 50 = 50000 但奇怪的是我的值如下:49962、49965、49366...

这是我的 C 代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define SHMSZ sizeof(int) /* Size of an integer*/

int main(){
    key_t key = 241096; /* Hard-coded key */
    int shm_id, sem_id, *shm;
    struct sembuf psem = {0, -1, 0};
    struct sembuf vsem = {0, 1, 0};

    if((shm_id = shmget(key, SHMSZ, IPC_CREAT | 0666)) == -1){
        printf("Err shmget");
        exit(1);
    }

    if((shm = shmat(shm_id, NULL, 0)) == (int *) -1){
        printf("Err shmat");
    }

    *shm = 0; /*Initilize the shared memory*/

    if((sem_id = semget(key, 1, IPC_CREAT | 0666)) == -1){
        printf("Err semget prg");
        exit(1);
    }

    /***Semaphore initialization****/
    semop(sem_id, &vsem, 1); /*set sem_value to 1*/
    /**********************************/

    int i;
    for (i = 0; i < 50; i++){
        pid_t pid = fork();
        if (pid == 0){
            int j;
            for (j = 0; j < 1000; j++){
                semop(sem_id, &psem, 1); /*wait for the semaphore*/
                *shm = *shm + 1;
                semop(sem_id, &vsem, 1); /* signal the semaphore*/
            }
            return 0; /*Whene done incrementing, return */
        }
    }
    while((wait(NULL) != -1)); /*Wait for all children to terminate*/
    printf("--%i--", *shm); /*Print the final value of the shared  memory*/
    return 0;
}

我尝试执行您的代码,它按预期打印了 50000。 尝试使用 ftok 和密钥在两个不同的共享内存之间生成非冗余密钥。

key_t key = ftok(FileName, AnyChar); // The program must have the right to access the file.

如果您在多次执行可执行文件时得到这些值,那肯定是因为您没有使用 ipcrm -a。此命令将删除您的程序创建的所有新 ipc。