关于共享内存,一般要做以下步骤
1.使用shmget建立共享内存空间
2.使用shmmat映射当前进程到开辟新的共享内存空间
3.读取或者写入数据到共享内存
3.删除共享内存空间
这个思路跟自己使用C语言中的malloc和free差不多,都是先申请后释放
当然C++/VC++/MFC都有相应的函数,只不过系统提供的有自动析构的函数,能够自动释放空间
看一下代码实例;
写入/读取的结构体:shm_com.h
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#ifndef _SHM
#define _SHM
#define SHM_READ 0
#define SHM_WRITE 1
#endif
#define TEXT_SHM 2048
struct shared_use
{
int n_write;
char sz_text[TEXT_SHM];
};
读取共享内存的数据shm_r.h
#include"shm_com.h"
int main(void)
{
int n_run=1;
void* p_shared_mem=(void*)0;
struct shared_use* st_shared_stuff;
int n_shmid;
n_shmid = shmget( (key_t)1234,sizeof(struct shared_use),0666|IPC_CREAT );
if(n_shmid==-1)
{
fprintf(stderr,"create share memory failed!\n");
exit(EXIT_FAILURE);
}
p_shared_mem=shmat(n_shmid,(void*)0,0);
if(p_shared_mem ==(void*)-1)
{
fprintf(stderr,"share momery mapping failed!\n");
exit(EXIT_FAILURE);
}
printf("Memory Address: %X\n",(int)p_shared_mem);
st_shared_stuff=(struct shared_use*)p_shared_mem;
//st_shared_stuff->sz_text=;
st_shared_stuff->n_write=SHM_READ;
while(n_run)
{
if(st_shared_stuff->n_write==SHM_WRITE)
{
printf("You write data:%s\n",st_shared_stuff->sz_text);
sleep(1);
st_shared_stuff->n_write=SHM_READ;
if(strncmp(st_shared_stuff->sz_text,"end",3)==0)
{
n_run = 0;
}
}
else
{
sleep(1);
printf("wait for write data\n");
}
}
if(shmdt(p_shared_mem)==-1)
{
fprintf(stderr,"delete share memory failed!\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
共享数据的写入 shm_w.c
#include"shm_com.h"
#define BUFFSIZE 1024
int main(void)
{
int n_run=1;
void* p_shared_mem=(void*)0;
struct shared_use* st_shared_stuff;
int n_shmid;
char sz_buff[BUFFSIZE];
n_shmid = shmget( (key_t)1234,sizeof(struct shared_use),0666|IPC_CREAT);
if(n_shmid==-1)
{
fprintf(stderr,"create share memory failed!\n");
exit(EXIT_FAILURE);
}
p_shared_mem=shmat(n_shmid,(void*)0,0);
if(p_shared_mem ==(void*)-1)
{
fprintf(stderr,"share momery mapping failed!\n");
exit(EXIT_FAILURE);
}
printf("Memory Address: %X\n",(int)p_shared_mem);
st_shared_stuff = (struct shared_use*)p_shared_mem;
while(n_run)
{
if(st_shared_stuff->n_write==SHM_WRITE)
{
sleep(1);
printf("wait for client data\n");
}
printf("Enter data: ");
fgets(sz_buff,BUFFSIZE,stdin);
strncpy(st_shared_stuff->sz_text,sz_buff,TEXT_SHM);
st_shared_stuff->n_write=SHM_WRITE;
if(strncmp(sz_buff,"end",3)==0)
{
n_run = 0;
}
}
if(shmdt(p_shared_mem)==-1)
{
fprintf(stderr,"delete share memory failed!\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
思考:
1.内存空间一定要在使用前初始化,不然会读取到意想不到的效果
2.共享数据时要保证数据的完整性,不能在写入时被另外进程读取(当然不考虑其他复杂问题)
3.全局变量、静态数据变量与共享内存的思考
4.父子进程共享的数据变量
5.类变量如class xx::static int n_page=1与全局变量int gn_page=2的区别