我正在尝试使用“shmget”创建一个结构数组以在父进程和子进程之间共享。我正在遵循我的教授的模板,但他的模板不包括结构和数组(共享内存仅存储一个 int)。以下代码编译时没有警告,但返回“0”作为输出,我期望看到“a 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;
}
最佳答案
我很惊讶你没有出现段错误:
- 您没有像 Nemo 指出的那样初始化 x
- 您的数组“列表”实际上是一个指向 Items 的指针数组,而不是一个 Items 数组。
- 最重要的是。在打印 y 中的值之前先分离共享内存。
代码应如下所示:
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;
}
关于c - 两个进程共享内存中的结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6326003/