C 中的共享内存和缺少 MAP_ANONYMOUS?

Shared memory in C and missing MAP_ANONYMOUS?

我正在编写一个 C 程序,我正在向 n 个玩家发牌,由 n 个分叉进程表示。我希望他们都共享同一副纸牌,所以我试图使用 mmap() 来跟踪纸牌大小,但是我必须为其编译该程序的机器不允许 MAP_ANONYMOUSMAP_ANON。有没有另一种方法可以将全局变量存储在仍然符合 C89/pre Linux 2.4 的共享内存中?

我的上下文程序:

static int *deck_size;

int pop(int *arr, int *size, int loc)
{
    int i;
    int val = arr[loc];
    for(i = loc; i < (*size - 1); i++)
    {
        arr[i] = arr[(i+1)];
        arr[*size] = '[=11=]';
    }
    *size = *size-1;
    return val;
}

int main(int argc, char* argv[])
{
    pid_t pid, wpid;
    int status, index, players, rdm_card;
    char outbuf[100];
    int deck[] = 
    {1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13};

    deck_size = mmap(NULL, sizeof *deck_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    *deck_size = 52;
    /* reject an execution with no arguments */
    if(argv[1] == NULL)
    {
        write(STDERR_FILENO, "Usage: dealer <n>\n", 18);
        exit(EXIT_FAILURE);
    }
    else
    {
        if( (players = atoi(argv[1])) < 1)
        {
            write(STDERR_FILENO, "n cannot be less than 1\n", 24);
            exit(EXIT_FAILURE);
        }
    }

    srand ( time(NULL) );

    rdm_card = rand() % *deck_size;

    for(index = 0; index < players; index++)
    {
        pid = fork();
        if (pid == 0) {
            sprintf(outbuf, "random card: %d\n", pop(deck, deck_size, rdm_card));
            write(STDOUT_FILENO, outbuf, 17);
            printf("size of deck %d!\n", *deck_size);
            exit(EXIT_SUCCESS);
        } else if (pid < 0) {
            write(STDERR_FILENO, "fork error\n", 11);
            exit(EXIT_FAILURE);
        } else {
            do {
                wpid = waitpid(pid, &status, WUNTRACED);
            } while (!WIFEXITED(status) && !WIFSIGNALED(status));
        }
    }
    return 0;
}

当您清楚地阅读手册页 MMAP(2) 时,它清楚地表明自 Linux 内核 2.4 以来支持 MAP_ANONYMOUS

The use of MAP_ANONYMOUS in conjunction with MAP_SHARED is supported on Linux only since kernel 2.4.

确保定义 _BSD_SOURCE_SVID_SOURCE 以获得 MAP_ANONYMOUS

#define _BSD_SOURCE