共享内存

共享内存直接操作物理内存,不需要拷贝,它通过向内核申请一块内存,映射到进程自身的虚拟地址空间中

可以直接读写这个进程的空间,提高效率。

可以通过ipcs -m 命令查看共享内存的有关信息。

写操作:

#include <stdio.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <string.h>
#include <sys/types.h>

#define BUFFER_SIZE 1024

int main()
{
	key_t key=ftok(".",1);
	if(key==-1)
	{
		printf("Create key failed\n");
		return -1;
	}	

    //申请获取一个共享内存
	int shmid=shmget(key,BUFFER_SIZE,IPC_CREAT|0666);
	if(shmid==-1)
	{
		printf("Create shmid failed\n");
		return -1;
	}

    //内存映射
	char *shmaddr=shmat(shmid,NULL,0);
	if(shmaddr==(void*)-1)
	{
		printf("Get shmaddr failed\n");
		return -1;
	}
	
	strcpy(shmaddr,"hello linux\n");

	return 0;

}

 

读操作:

#include <stdio.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <string.h>
#include <sys/types.h>

#define BUFFER_SIZE 1024

int main()
{
	key_t key=ftok(".",1);
	if(key==-1)
	{
		printf("Create key failed\n");
		return -1;
	}	

    //申请一块共享内存
	int shmid=shmget(key,BUFFER_SIZE,IPC_CREAT|0666);
	if(shmid==-1)
	{
		printf("Create shmid failed\n");
		return -1;
	}

    //把申请的共享内存链接到内核的某一个地址上(内存映射)
	char *shmaddr=shmat(shmid,NULL,0);
	if(shmaddr==(void*)-1)
	{
		printf("Get shmaddr failed\n");
		return -1;
	}

	printf("Data is:%s\n",shmaddr);
    printf("shmid is:%d\n",shmid);

    //删除共享内存
	shmctl(shmid,IPC_RMID,NULL);

	return 0;

}

输出端:

共享内存