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」正在給出。請任何人解釋這個..
不同的進程有不同的內存映射。請記住,在現代系統中,內存是* virtual *,任何地址都可以用於任何內存。 –