2017-03-13 28 views
0

寫:共享內存如何通過使用不同的內存地址共享數據?

#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」正在給出。請任何人解釋這個..

+1

不同的進程有不同的內存映射。請記住,在現代系統中,內存是* virtual *,任何地址都可以用於任何內存。 –

回答

0

內核處理這個。

您從用戶空間看到的所有內存都稱爲「虛擬內存」。它們可以是未分配的(如果沒有寫入),在真實RAM上分配,在交換時分配,或者指向內存映射文件或共享內存。操作系統負責將它們映射到物理內存地址。

當內存共享時,頁面被映射到不同的虛擬內存地址,但在內部它們共享相同的物理頁面。