进程间通信之共享内存 (二)

2014-11-24 00:36:53 · 作者: · 浏览: 6
x00;
}


int getshareshm()
{
int shm_id;
int lx = 0;
int zt = 0;
sharem *p_map;

shm_id=shmget(shmkey,4096,0666);
if(shm_id==FAIL)
{
DBG(DBG_ERROR, "creat shm is fail\n");
perror("error");
return FAIL;
}

p_map = (sharem*)shmat(shm_id,NULL,0);

lx = (*p_map).lx;
zt = (*p_map).zt;

printf("lx = %d, zt = %d\n", lx, zt);

if(shmdt(p_map)==FAIL)
return FAIL;

return zt;

}

void sharememory()
{
static int count = 0;
setshareshm(count, 0);
count++;
getshareshm();
}

int main(void)
{
createShm();

while (1)
{
sharememory();
usleep(10*1000);
}
return 0;
}

#include
#include
#include
#include
#include
#include
#include
#include
#include

int sharememorycom;

//调试打印宏定义
#define DBG(level,fmt,para...) \
{ \
if(level) \
printf(fmt "\tFrom FileName:%s Function:%s Line:%d\n" , ##para, __FILE__, __FUNCTION__, __LINE__); \
}

#define DBG_INFOR 0x01 //正常打印信息
#define DBG_WARNING 0x02 //处理警告异常
#define DBG_ERROR 0x04 //处理错误

#define SUCCESS 1
#define FAIL -1

typedef struct
{
int lx;
int zt;
} sharem;

key_t shmkey;

int createShm()
{
int shm_id = 0;
static char *shmname = "aaa";

shmkey = ftok(shmname,0);
if(shmkey==FAIL)
{
DBG(DBG_ERROR, "get shm key failure!\n");
return FAIL;
}

shm_id=shmget(shmkey,4096,IPC_CREAT|0666);
if(shm_id==FAIL)
{
DBG(DBG_ERROR, "creat shm is fail\n");
perror("error");
return FAIL;
}

return SUCCESS;
}


int setshareshm(int lx,int zt)
{
int shm_id;

sharem *p_map;

shm_id=shmget(shmkey,4096,0666);
if(shm_id==FAIL)
{
DBG(DBG_ERROR, "creat shm is fail\n");
perror("error");
return FAIL;
}

p_map=(sharem*)shmat(shm_id,NULL,0);

(*p_map).lx=lx;
(*p_map).zt=zt;

if(shmdt(p_map)==FAIL)
return FAIL;

return 0x00;
}


int getshareshm()
{
int shm_id;
int lx = 0;
int zt = 0;
sharem *p_map;

shm_id=shmget(shmkey,4096,0666);
if(shm_id==FAIL)
{
DBG(DBG_ERROR, "creat shm is fail\n");
perror("error");
return FAIL;
}

p_map = (sharem*)shmat(shm_id,NULL,0);

lx = (*p_map).lx;
zt = (*p_map).zt;

printf("lx = %d, zt = %d\n", lx, zt);

if(shmdt(p_map)==FAIL)
return FAIL;

return zt;

}

void sharememory()
{
static int count = 0;
setshareshm(count, 0);
count++;
getshareshm();
}

int main(void)
{
createShm();

while (1)
{
sharememory();
usleep(10*1000);
}
return 0;
}