#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
/*
MAP_SHARED: 映射区的数据直接反映到文件中
MAP_PRIVATE:映射区的数据不会反映到文件中
*/
struct msg
{
char name[20];
int age;
};
int main()
{
int fd = open("obj",O_RDWR|O_CREAT,0664);
if(fd == -1) perror("open"),exit(-1);
int ret = ftruncate(fd,sizeof(struct msg)*20);
if(ret == -1) perror("ftruncate"),exit(-1);
void* pp = mmap(NULL,sizeof(struct msg),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
struct msg* p =pp;
for(int i = 0;i<20;i++)
{
strcpy(p->name,"袁苏东!\n");
p->age= 10;
p++;
}
munmap(pp,sizeof(struct msg)*20);
close(fd);
return 0;
}
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
/*
MAP_SHARED: 映射区的数据直接反映到文件中
MAP_PRIVATE:映射区的数据不会反映到文件中
*/
struct msg
{
char name[20];
int age;
};
int main()
{
int fd = open("obj",O_RDWR|O_CREAT,0664);
if(fd == -1) perror("open"),exit(-1);
int ret = ftruncate(fd,sizeof(struct msg)*20);
if(ret == -1) perror("ftruncate"),exit(-1);
void* pp = mmap(NULL,sizeof(struct msg),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
struct msg* p =pp;
for(int i = 0;i<20;i++)
{
strcpy(p->name,"袁苏东!\n");
p->age= 10;
p++;
}
munmap(pp,sizeof(struct msg)*20);
close(fd);
return 0;
}