写:
#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”正在给出。请有人解释一下..
答案 0 :(得分:0)
内核处理这个问题。
您从用户空间看到的所有内存都被称为&#34;虚拟内存&#34;。它们可以是未分配的(如果没有写入),分配在实际RAM上,在交换时分配,或指向内存映射文件或共享内存。操作系统负责将它们映射到物理内存地址。
当共享内存时,页面会映射到不同的虚拟内存地址,但在内部它们共享同一个物理页面。