[Linux学习]Linux下进程通讯之共享内存

本文用两份代码,一个创建共享内存并向其中写入相关的数据,一个获取共享内存并读取其中的数据,下面上代码:

server.c:获取共享内存,并向共享内存中写入数据

#include <sys/types.h>  
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>

#define BUF_SIZE 1024
#define MYKEY 25

struct st_person
{
int age;
char name[10];
};

int main()
{
int shmid;
struct st_person *shmptr;
//申请共享内存
if((shmid = shmget(MYKEY,BUF_SIZE,IPC_CREAT)) ==-1)
{
printf("shmget error \n");
exit(1);
}
//连接共享内存
if((shmptr = (struct st_person*)shmat(shmid,0,0))==(void *)-1)
{
printf("shmat error!\n");
exit(1);
}
//向共享内存写入信息
shmptr->age = 10;
memcpy(shmptr->name,"alephsoul", sizeof(char)*10);
printf("age:%d\n", shmptr->age);
printf("name:%s\n", shmptr->name);
//解绑内存
shmdt(shmptr);

scanf("%s",shmptr);

exit(0);
}

client.c:获取server.c创建的共享内存,并读取server.c向共享内存中写入的数据。

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define BUF_SIZE 1024
#define MYKEY 25

struct st_person
{
int age;
char name[];
};

int main()
{
int shmid;
struct st_person *shmptr;

if((shmid = shmget(MYKEY,0,0)) == -1)
{
printf("shmget error!\n");
exit(1);
}

if((shmptr = (struct st_pesrson*)shmat(shmid,0,0)) == (void *)-1)
{
printf("shmat error!\n");
exit(1);
}

while(1)
{
printf("age:%d;\n", shmptr->age);
printf("name:%s\n;", shmptr->name);
sleep(3);
}
exit(0);
}




posted @ 2012-03-27 22:25  邵贤军  阅读(365)  评论(0编辑  收藏  举报