我正在尝试创建一个结构数组,以便使用“shmget”在父进程和子进程之间共享。我正在关注我教授的模板,但他没有包含结构和数组(共享内存只存储了一个int)。以下代码编译时没有警告但返回“0”作为输出,我期望看到“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;
}
答案 0 :(得分:1)
我很惊讶你以后没有发生过段错误:
代码应如下所示:
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;
}