在共享内存中,据我所知,使用shmat()
调用连接到它的两个进程之间共享相同的逻辑地址。那么为什么我为下面的程序获得不同的内存地址(在输出中),即使它们共享相同的地址。
// Shm_Server.C
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXSIZE 27
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
char c;
int shmid;
key_t key = 5678;
char *shm_addr, *s;
if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
die("shmget");
if ((shm_addr = (char *)shmat(shmid, NULL, 0)) == (char *) -1)
die("shmat");
printf("\nServer shm_addr = %x\n",shm_addr);
s = shm_addr;
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
while (*shm_addr != '*')
sleep(1);
if((shmctl(shmid, IPC_RMID, 0)) < 0)
die("shmctl");
exit(0);
}
// Shm_Client.C
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXSIZE 27
void die(char *s)
{
perror(s);
exit(1);
}
int main()
{
int shmid;
key_t key = 5678;
char *shm_addr, *s;
if ((shmid = shmget(key, 0, 0666)) < 0)
die("shmget");
if ((shm_addr = (char *) shmat(shmid, NULL, 0)) == (char *) -1)
die("shmat");
printf("\nClient shm_addr = %x\n", shm_addr);
//reading what the server put in shared memory
for (s = shm_addr; *s != '\0'; s++)
putchar(*s);
putchar('\n');
//Writing in shared memory
*shm_addr = '*';
exit(0);
}
输出:
[xyz@xyz:Shm_ex] $ ./Shm_Server &
[1] 19489
[xyz@xyz:Shm_ex] $
Server shm_addr = d92b5000
./Shm_Client
Client shm_addr = eb3c4000
abcdefghijklmnopqrstuvwxyz
[xyz@xyz:Shm_ex] $
答案 0 :(得分:2)
在共享内存中,据我所知,共享相同的逻辑地址 使用shmat()调用附加到它的两个进程之间。
据我了解,在共享内存中,相同的物理地址在多个连接到它的进程之间共享。该物理地址映射到相应进程的所有虚拟地址空间。因此,shmat()
将返回不同的逻辑地址。