注意:以下编译加上 -lrt
例如:gcc -o server server.c -lrt
1.创建一个共享内存区的例子
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
int main( int argc, char ** argv )
{
intshm_id;
if( argc !=2 )
{
printf("请输入共享区名称!\n");
exit(EXIT_FAILURE );
}
if( ( shm_id= shm_open( argv[1], O_CREAT | O_RDWR, 0644 ) ) <= 0)
{ //!> 创建共享区
printf("创建共享区失败...\n");
exit(EXIT_FAILURE );
}
printf("共享区ID == %d \n", shm_id );
shm_unlink(argv[1] ); //!> 删除共享区
return0;
}
2.使用mmap映射将一个文件中内容cp到一个新建的文件
注意:必须有一个现有的 old 文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
int main( int argc, char ** argv )
{
int fd_in,fd_out; //!> 源文件和新建的文件 文件描述符
void *src; //!> 源
void *des; //!> 目的
struct statstat_buf; //!> 文件信息结构体
if( argc !=3 ) //!> 注意参数:2个文件名
{
printf("请输入两个文件名!\n");
exit(EXIT_FAILURE );
}
if( ( fd_in= open( argv[1], O_RDONLY ) ) < 0) //!> 打开源文件
{