两个进程共享内存中的结构体数组
我正在尝试使用“shmget”创建一个结构数组以在父进程和子进程之间共享。我正在遵循我的教授的模板,但他的模板不包括结构和数组(共享内存仅存储一个 int)。以下代码编译时没有警告,但返回“0”作为输出,我期望看到“a 10”。我做错了什么?
另外,当我尝试在子进程中声明新变量时,我遇到了麻烦,我已经看到了其他可以工作的示例,但我不知道为什么我每次都被迫在分叉之前声明它们。
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;
}
I'm trying to create an array of structs to share between a parent and child process using "shmget". I am following a template from my professor, but his did not include structs and arrays (the shared memory only stored an int). The following code compiles without warnings but returns " 0" as the output, I am expecting to see "a 10". What am I doing wrong?
Also I am having trouble when i try to declare new variables inside the child processes, I have seen other samples where it works but I don't know why I am being forced to declare them before the fork everytime.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很惊讶你没有出现段错误,因为:
代码应该如下所示:
I am surprised that you didn't segfault since:
The code should look like this: