gpt4 book ai didi

c - 共享内存是如何通过不同的内存地址来共享数据的呢?

转载 作者:行者123 更新时间:2023-11-30 16:48:58 25 4
gpt4 key购买 nike

写:

#include "apue.h"
#include "errorlog.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main ()
{
int segment_id;
char* shared_memory;
struct shmid_ds *shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
shmbuffer=malloc(sizeof(struct shmid_ds));
/* Allocate a shared memory segment. */
if((segment_id = shmget (12345, shared_segment_size,IPC_CREAT|S_IRUSR | S_IWUSR))==-1)
perror("shmget");
/* Attach the shared memory segment. */
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
/* Determine the segment's size. */
shmctl (segment_id, IPC_STAT, shmbuffer);
segment_size = shmbuffer->shm_segsz;
printf ("segment size: %d\n", segment_size);
/* Write a string to the shared memory segment. */
sprintf (shared_memory, "Hello, world.");
/* Detach the shared memory segment. */
shmdt (shared_memory);
return 0;
}

输出:

shared memory attached at address 0xb77ab000
segment size: 25600

阅读:

#include "apue.h"
#include "errorlog.h"
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main ()
{
int segment_id;
char* shared_memory;
struct shmid_ds *shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
shmbuffer=malloc(sizeof(struct shmid_ds));
/* Allocate a shared memory segment. */
segment_id = shmget (12345, shared_segment_size,
IPC_CREAT | S_IRUSR | S_IWUSR);

/* Attach the shared memory segment, at a different address. */
shared_memory = (char*) shmat (segment_id, (void*)0, 0);
printf ("shared memory reattached at address %p\n", shared_memory);
/* Print out the string from shared memory. */
printf ("%s\n", shared_memory);
/* Detach the shared memory segment. */
shmdt (shared_memory);
printf("current proc id %d",getpid());
return 0;
}

输出:

shared memory reattached at address 0xb7783000
Hello, world.
current proc id 6530

我已经执行了这个共享内存的程序。我有一个疑问,不同的内存地址如何得到相同的数据。这里写入地址是0xb77ab000,读取地址是0xb7783000,但是给出了正确的数据“Hello, world”。请任何人解释一下这一点..

最佳答案

内核处理这个。

您从用户空间看到的所有内存都称为“虚拟内存”。它们可以是未分配的(如果没有写入任何内容)、在实际 RAM 上分配、在交换上分配、或指向内存映射文件或共享内存。操作系统负责将它们映射到物理内存地址。

当内存被共享时,页面被映射到不同的虚拟内存地址,但在内部它们共享相同的物理页面。

关于c - 共享内存是如何通过不同的内存地址来共享数据的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42759037/

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