#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/shm.h>
#define ARRAY_SIZE 40000
#define MALLOC_SIZE 100000
#define SHM_SIZE 100000
#define SHM_MODE 0644
char array[ARRAY_SIZE]; //未初始化的数据,保存在未初始化数据段
char array2[ARRAY_SIZE]={1,2,3}; //初始化的数据,保存在初始化数据段
int main(void)
{
int shmid;
char *ptr,*shmptr;
char array3[ARRAY_SIZE];
printf("array[] from %x to %x\n",(unsigned)&array[0],(unsigned)&array[ARRAY_SIZE]);
printf("array2[] from %x to %x\n",(unsigned)&array2[0],(unsigned)&array2[ARRAY_SIZE]);
printf("array3[] from %x to %x\n",(unsigned)&array3[0],(unsigned)&array3[ARRAY_SIZE]);
printf("stack around:shmid %x,ptr %x,shmptr %x\n",(unsigned)&shmid,(unsigned)&ptr,(unsigned)&shmptr);
if((ptr=malloc(MALLOC_SIZE))==NULL)
{
perror("malloc");
exit(-1);
}
printf("malloc from %x to %x\n",(unsigned)ptr,(unsigned)ptr+MALLOC_SIZE);
if((shmid=shmget(IPC_PRIVATE,SHM_SIZE,SHM_MODE))<0)
{
perror("shmget");
exit(-1);
}
if((shmptr=shmat(shmid,0,0))==(void *)-1)
{
perror("shmat");
exit(-1);
}
printf("shared memory attached from %x to %x\n",(unsigned)shmptr,(unsigned)shmptr+SHM_SIZE);
if(shmctl(shmid,IPC_RMID,0)<0)
{
perror("shmctl");
exit(-1);
}
return 0;
}
|