shm_open打开共享内存文件

1 .shm_open:创建内存文件,路径要求类似/filename,以/起头,然后文件名,中间不能带/。
shm_open函数的原型和头文件如下:

NAME
       shm_open, shm_unlink - create/open or unlink POSIX shared memory objects

SYNOPSIS
       #include 
       #include         /* For mode constants */
       #include            /* For O_* constants */

       int shm_open(const char *name, int oflag, mode_t mode);

       int shm_unlink(const char *name);
       //删除打开的文件描述符
		
       Link with -lrt.
       //注意编译时候要加上该链接库,如:
       gcc a.out -o a -lrt
RETURN VALUE
       On success, shm_open() returns a nonnegative file descriptor.  On failure, shm_open() returns -1.
       shm_unlink() returns 0 on success, or -1 on error.

示例代码:
向共享内存中写文件:
编译:gcc shm_open_w.c -o shm_open_w -lrt

/*************************************************************************
	* File Name: shm_open_w.c
	* Author: lixiaogang
	* Mail: [email protected] 
	* Created Time: 2017年06月09日 星期五 19时09分20秒
 ************************************************************************/

#include
#include
#include
#include
#include
#include
#include
#include

/*封装打印出错函数*/
void sys_err(const char *str,int num){
	perror(str);
	exit(num);
}

int main(int argc,char *argv[])
  {
	int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777);
	/*O_EXCL|O_CREAT,若文件已经存在,则报错*/
	if(fd < 0){
		fd = shm_open("/hello.txt",O_RDWR,0777);
		/*直接打开文件读写*/
	}else
		ftruncate(fd,4096);
		/*若为自己创建的文件,则为文件分配内存空间大小*/
	void *ptr = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	
	puts("start writeing  data....");
	/*这里为写文件*/
	strcpy((char*)ptr,"i am lixiaogang");
	puts("write over");
	getchar();
	shm_unlink("/hello.txt");
	close(fd);
    return 0;
  }


向共享内存中读文件
编译:gcc shm_open_r.c -o shm_open_r -lrt

/*************************************************************************
	* File Name: shm_open_r.c
	* Author: lixiaogang
	* Mail: [email protected] 
	* Created Time: 2017年06月09日 星期五 19时09分20秒
 ************************************************************************/

#include
#include
#include
#include
#include
#include
#include
#include

void sys_err(const char *str,int num){
	perror(str);
	exit(num);
}

int main(int argc,char *argv[])
  {
	int fd = shm_open("/hello.txt",O_RDWR|O_CREAT|O_EXCL,0777);
	if(fd < 0){
		fd = shm_open("/hello.txt",O_RDWR,0777);
	}else
		ftruncate(fd,4096);
	void *ptr = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	
	puts("start reading data....");
	puts((char*)ptr);
	puts("read over");
	shm_unlink("/hello.txt");
	close(fd);
    return 0;
  }



你可能感兴趣的:(Linux应用开发)