本文用兩份代碼,一個建立共用記憶體並向其中寫入相關的資料,一個擷取共用記憶體並讀取其中的資料,下面上代碼:
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);
}