posix 基于文件的共享内存

来源:互联网 发布:nba2k14mc数据没有 编辑:程序博客网 时间:2024/06/05 19:38
#include <sys/ipc.h>#include <sys/shm.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <string.h>#include <stdio.h>#include <semaphore.h>#include <fcntl.h>#include <sys/mman.h>#include <stdlib.h>#include <error.h>#include <sys/stat.h>int main(){int fd, ret;int mlength = 128;char name[] = "11";char buf[256]= "mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm";char *mm;struct stat stat1,stat2;fd = open(name, O_CREAT|O_RDWR,0666);if( -1 == fd ){perror("open error");return -1;}    //         ret = fstat(fd, &stat1);if( 0 != ret ){perror("fstat error");return -1;}printf("%s file rooms are %lu \n", name, stat1.st_size);    if( stat1.st_size < mlength ){    ret = ftruncate(fd, mlength);if( -1 == ret ){perror("ftruncate error");return -1;}}         ret = fstat(fd, &stat2);if( 0 != ret ){perror("fstat error");return -1;}printf("%s file rooms are %lu \n", name, stat2.st_size);mm = (char *)mmap(NULL, mlength, PROT_READ|PROT_WRITE, MAP_SHARED, fd,0);if( MAP_FAILED == mm ){perror("mmap error");return -1;}close(fd);//printf("%s \n", mm);//mm[0] = 'F';int i;for( i=0; i<128; i++ ){buf[i] = i%10 + '0';}buf[128] = '\0';strncpy(mm,buf,mlength);         if( -1 == msync(mm, mlength, MS_SYNC) ){perror("msync error");return -1;}printf("%s \n", mm);if( -1 ==  munmap(mm, mlength) ){perror("munmap error ");return -1;}    return 0;}

代码有点乱, 主要看步骤
原创粉丝点击