gpt4 book ai didi

c - 如何在同一个共享内存段中正确地拥有多个变量

转载 作者:行者123 更新时间:2023-12-04 08:29:31 25 4
gpt4 key购买 nike

我试图在同一个内存段中有 2 个整数。我的代码如下:

int main()
{
int *a;
int *b;
int id;
id = shmget(IPC_PRIVATE,10,0666);
a = (int *) shmat(id, (void*)0, 0);
b = (int *) shmat(id, (void*)0, 0);
*a = 5;
*b = 10;
printf("%d\n",*a);
printf("%d\n",*b);
}
这将打印 10 两次。谁能解释一下为什么会发生这种情况以及如何解决?
额外的问题:如果我有 char * 而不是 int 是否有必要做 malloc(sizeof(char)*10) 或者 shmat 调用以某种方式完成这项工作?
提前致谢!

最佳答案

首先,你总是想使用malloc而不是尽可能共享内存。
即使在进行 IPC 时,简单的管道通常也更有效。
回到你的问题,这里有一些对你的代码的解释

int main()
{
int *a;
int *b;
int id;

/* 'shmget' creates a shared memory segments of size 10,
basically reserving 10 bytes of RAM/Swap. This memory is not
accessible in your virtual memory yet */
id = shmget(IPC_PRIVATE,10,0666);

/* `shmat` maps the shared memory from above and makes it accessible in
your virtual memory. `a` points to the beginning of the memory segment */
a = (int *) shmat(id, (void*)0, 0);

/* Here we map the same shared memory again into a different place in the
virtual memory. But even if `a` and `b` points to different memory
addresses, those addresses are backed by the same segment in RAM/Swap */
b = (int *) shmat(id, (void*)0, 0);

*a = 5;
*b = 10; /* because `*a` and `*b` are backed by the same RAM/Swap, */
/* this will allso overwrite `*a` */

printf("%d\n",*a);
printf("%d\n",*b);
}
要解决这个问题,您基本上有两种选择。要么有两个共享内存段,一个用于 a一个用于 b .或者你制作一个足够大的段来容纳两个 ab指向段中的不同位置:
第一个解决方案:
/* This uses two segments */
int *a;
int *b;
int id1;
int id2;
id1 = shmget(IPC_PRIVATE,sizeof(int),0666);
id2 = shmget(IPC_PRIVATE,sizeof(int),0666);
a = (int *) shmat(id1, (void*)0, 0);
b = (int *) shmat(id2, (void*)0, 0);
第二种解决方案:
/* This uses one segments */
int *a;
int *b;
int id;
/* Allocate enough memory for 2 int */
id = shmget(IPC_PRIVATE, 2*sizeof(int), 0666);
/* Map that memory into virtual memory space */
a = (int *) shmat(id, (void*)0, 0);
/* `a` points to the first int in a sequence of 2 ints, let `b` point to
the next one. */
b = a + 1;
与往常一样,为简洁起见,此代码省略了错误检查。添加错误检查留给读者作为练习。
对于额外的问题, malloc或者任何共享内存函数都关心你将在分配的内存中存储什么。他们只是给你一个 char 的序列.你的工作是计算多少 char你需要。 (顺便说一句 sizeof(char) 总是 1)

关于c - 如何在同一个共享内存段中正确地拥有多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65092632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com