mmap/shm_open 映射进程间共享文件

来源:互联网 发布:mac地址可以重复么 编辑:程序博客网 时间:2024/05/16 17:16

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{    
    int fd = shm_open("tset.txt", O_CREAT|O_RDWR, 0777);//需要连接 -lrt  
    if(fd==0) 
    {    
perror("open error");   
}       
ftruncate(fd, 1024);//修改文件长度    
mmap(NULL, 1024, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);//设置共享映射           
write(fd, "hello", 6);   
char buf[1024];
    read(fd, buf, 6);
    printf("%s\n",buf);
return 0;
}

0 0
原创粉丝点击