Why are these two addresses not the same?
shmget.c:
#include<sys/types.h>
#include<string.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
main()
{
key_t key;
int shmid;
char* addr1;
key = ftok("/home/tamil/myc/pws.c",'T');
shmid = shmget(key,128*1024,IPC_CREAT|SHM_R|SHM_W);
addr1 = shmat(shmid,0,0);
printf("\nIPC SHARED MEMORY");
printf("\n SENDER ADDRESS");
printf("\nTHE ADDRESS IS %p",addr1);
printf("\nENTER THE MESSAGE:");
scanf("%s",addr1);
printf("\nMESSAGE STORED IN %p IS %s",addr1,addr1);
}
shmget2.c:
#include<sys/types.h>
#include<string.h>
#include<sys开发者_如何学C/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
main()
{
int shmid;
char* addr1;
key_t key;
key = ftok("/home/tamil/myc/pws.c",'T');
shmid = shmget(key,128*1024,SHM_R|SHM_W);
addr1 = shmat(shmid,0,0);
printf("\nIPC SHARED MEMORY");
printf("\n SENDER ADDRESS");
printf("\nTHE ADDRESSS IS %p",addr1);
printf("\nMESSAGE STORED IN %p IS %s",addr1,addr1);
}
Output:
tamil@ubuntu:~/myc$ cc shmget.c
tamil@ubuntu:~/myc$ ./a.out
IPC SHARED MEMORY
SENDER ADDRESS
**THE ADDRESS IS **0xb786c000****
ENTER THE MESSAGE:helloworld
MESSAGE STORED IN **0xb786c000** IS helloworldtamil@ubuntu:~/myc$ cc shmget2.c
tamil@ubuntu:~/myc$ ./a.out
IPC SHARED MEMORY
SENDER ADDRESS
**THE ADDRESSS IS **0xb7706000****
MESSAGE STORED IN **0xb7706000** IS helloworldtamil@ubuntu:~/myc$
This all works well. But the address is not the same. Why is this?
Shared memory can be mapped to different regions in the address space of different processes. This is perfectly normal. But if you're storing pointers inside the shared memory to other parts of the shared memory, then you're in trouble. You'll need to use something like an offset pointer in that case.
The addresses you're seeing are different because they are virtual. Each process gets a 'pretend' address space that is contiguous (no gaps) and can be made larger over time. In reality, the virtual addresses can be mapped to different parts of RAM in chunks. Have a look here for more detail (in particular, this diagram). In the case of shared memory, there is a single area of RAM that can be 'seen' by both processes. However, it is perfectly normal for the addresses to look different to each process.
Here's the idea:
0x00 0x01 0x07 0xff
Process 2 Virtual: +--+-----------------+------------------+
| |
RAM Physical Addr: 0x04 +-----shared------+ 0x0a
| |
Process 1 Virtual: +-------+-----------------+---------+
0x00 0x09 0x0f 0xff
(Not drawn to scale :) Note that process 1 and 2 share the same area of RAM (physical address 0x04 through 0x0a), but that shared piece of RAM is mapped to different parts of their virtual address spaces (0x09 through 0x0f for P1; 0x01 through 0x07 for P2).
精彩评论