繁体   English   中英

两个进程的共享 memory 中的结构数组

[英]Array of structs in shared memory for two processes

我正在尝试使用“shmget”创建一个结构数组以在父进程和子进程之间共享。 我正在遵循我教授的模板,但他不包括结构和 arrays(共享的 memory 只存储了一个 int)。 以下代码编译时没有警告,但返回“0”作为 output,我希望看到“10”。 我究竟做错了什么?

此外,当我尝试在子进程中声明新变量时也遇到了麻烦,我已经看到了其他示例,但我不知道为什么我每次都被迫在 fork 之前声明它们。

typedef struct { 
    char character;
    int number;
} item;

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

    mem_id = shmget(IPC_PRIVATE, 10*sizeof(item), SHM_R | SHM_W);
    item * x;
    item * y;
    item * list[10];

    switch(fork())
    {
        case -1:
            perror("Bad fork()"); exit(1);
        case 0:
            *list = shmat(mem_id, NULL, 0);
            if ((int *) list == (int *) -1)
            {perror("Child cannot attach"); exit(1);}           

            x->character = 'a';
            x->number = 10;

            list[0] = x;

            shmdt(list);
            exit(0);
        default:
            *list = shmat(mem_id, NULL, 0);
            if ((int *) list == (int *) -1)
            {perror("Child cannot attach"); exit(1);}

            wait((int *)0);
            y = list[0];
            shmdt(list);

            printf("%c %d\n", y->character, y->number);

            if (shmctl(mem_id, IPC_RMID, 0) <0)
                { perror("cannot remove shared memory"); exit(1);}

            return 0;
    }
    return 0;
}

我很惊讶你没有出现段错误,因为:

  1. 您没有像 Nemo 指出的那样初始化 x
  2. 您的数组“列表”实际上是一个指向 Items 的指针数组,而不是一个 Items 数组。
  3. 最重要的是。 在打印 y 中的值之前,您分离共享的 memory。

代码应如下所示:

typedef struct { 
    char character;
    int number;
} item;

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

    mem_id = shmget(IPC_PRIVATE, 10*sizeof(item), SHM_R | SHM_W);
    item *x;
    item *y;
    item *list;

    switch(fork())
    {
    case -1:
        perror("Bad fork()"); exit(1);
    case 0:
        list = (item *)shmat(mem_id, NULL, 0);
        if ((void *) -1 == (void *)list)
        {
            perror("Child cannot attach"); exit(1);
        }
        x = list;
        x->character = 'a';
        x->number = 10;

        shmdt(list); // No need for this
        exit(0);
    default:
        list = (item *)shmat(mem_id, NULL, 0);
        if ((void *) list == (void *) -1)
        {
           perror("Child cannot attach"); exit(1);
        }

        wait((int *)0);
        y = list;
        printf("%c %d\n", y->character, y->number);

        shmdt(list);

        if (shmctl(mem_id, IPC_RMID, 0) <0)
            { perror("cannot remove shared memory"); exit(1);}

        return 0;
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM