#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
typedef struct stu
{
char name[20];
int age;
}STU;
int main(void)
{
int shmid;//共享内存文件描述符
//创建共享内存
shmid = shm_open("/xyz", O_CREAT | O_RDWR, 0666);
if(shmid ==-1)
ERR_EXIT("shm_open");
printf("shm_open success\n");
//修改共享内存的大小,将其变为学生结构体的大小
if(ftruncate(shmid, sizeof(STU)) == -1)
ERR_EXIT("ftruncate");
//获取共享内存的信息
struct stat buf;
if(fstat(shmid, &buf) == -1)
ERR_EXIT("fstat");
printf("size=%ld mode =%o\n", buf.st_size, buf.st_mode & 07777);
close(shmid);//关闭共享内存
//删除共享内存的对象
//shm_unlink("/xyz");
return 0;
}
//使用共享内存对象进行写入信息
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
typedef struct stu
{
char name[20];
int age;
}STU;
int main(void)
{
int shmid;//共享内存文件描述符
//打开共享内存对象
//当mmap共享内存函数设置为PROT_WRITE, MAP_SHARED
//shm_open必须以O_RDWR方式打开
shmid = shm_open("/xyz", O_RDWR, 0);
if(shmid ==-1)
ERR_EXIT("shm_open");
printf("shm_open success\n");
//获取共享内存的信息
struct stat buf;
if(fstat(shmid, &buf) == -1)
ERR_EXIT("fstat");
printf("size=%ld mode =%o\n", buf.st_size, buf.st_mode & 07777);
//将共享内存对象映射到进程地址空间,才能使用对象进行通信
STU *p;
//利用mmap进行映射
//NULL为映射的起始地址
//len映射到进程地址空间的字节数
//prot:映射区的保护方式
//flags:标志
//fd:文件描述符
//offset:从文件头开始的偏移量
p = mmap(NULL, buf.st_size, PROT_WRITE, MAP_SHARED, shmid, 0);
if(p==MAP_FAILED)
ERR_EXIT("mmap");
//向共享区填写内容
strcpy(p->name, "test");
p->age = 23;
close(shmid);//关闭共享内存对象
//删除共享内存的对象
//shm_unlink("/xyz");
return 0;
}
//使用共享内存对象进行读取信息
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
typedef struct stu
{
char name[20];
int age;
}STU;
int main(void)
{
int shmid;//共享内存文件描述符
//打开共享内存对象
shmid = shm_open("/xyz", O_RDONLY, 0);
if(shmid ==-1)
ERR_EXIT("shm_open");
printf("shm_open success\n");
//获取共享内存的信息
struct stat buf;
if(fstat(shmid, &buf) == -1)
ERR_EXIT("fstat");
printf("size=%ld mode =%o\n", buf.st_size, buf.st_mode & 07777);
//获取共享内存对象的信息
STU *p;
p = mmap(NULL, buf.st_size, PROT_READ, MAP_SHARED, shmid, 0);
if(p==MAP_FAILED)
ERR_EXIT("mmap");
//向共享区填写内容
printf("name=%s age=%d\n",p->name, p->age);
close(shmid);//关闭共享内存对象
//删除共享内存的对象
//shm_unlink("/xyz");
return 0;
}