linux学习笔记8-共享内存

共享内存

  共享内存是由系统内核出于在多个进程间交换数据留出的一块内存区域.一个进程创建,其他进程也可以进行读写.
  

man shmget

//所需头文件
#include <sys/ipc.h>
#include <sys/shm.h>

//key是IPC_PRIVATE size指定共享内存的大小 shmflg为权限
int shmget(key_t key, size_t size, int shmflg);

shmget使用

#include <stdio.h>
#include <stdlib.h>

#include <sys/ipc.h>
#include <sys/shm.h>

int main(int argc,char *argv[])
{
	int shm_result = shmget(IPC_PRIVATE,1024,0666);  //创建共享内存
	if(shm_result < 0)
	{
		printf("share memory failed!\n");
	}
	else 
	{
		printf("share meory success!\n");
	}
	return 0;
}

使用ipcs -m查看

ipcs -m 查看共享内存

附加和分离共享内存

#include <stdio.h>
#include <stdlib.h>

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

int main(int argc,char *argv[])
{
	char *buf;
	int shm_id = 0;
	if(argc < 2)
	{
		return -1;
	}
	shm_id =atoi(argv[1]);      //获取共享内存的编号,具体使用ipcs -m命令查看
	buf = shmat(shm_id,0,0);    //根本编号附加到共享内存上
	sleep(10);                  //休眠10秒钟,方便ipcs -m查看nattach
	shmdt(buf);                 //让进程与共享内存分离
	return 0;
}

共享内存使用场景

#include <stdio.h>
#include <stdlib.h>

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

int main(int argc,char *argv[])
{
	char *buf;
	int shm_id = 0;
	if(argc < 3)
	{
		return -1;
	}
	shm_id =atoi(argv[1]);
	buf = shmat(shm_id,0,0);      //让进程附加共享内存
	if(atoi(argv[2]) == 1)        //参数为1时,为输入
	{
		scanf("%s\n",buf);
	}
	if(atoi(argv[2]) == 2)        //参数为2时,为输出
	{
		printf("%s\n",buf);
	}
	shmdt(buf);                 //让进程与共享内存分离
	return 0;
}

shmat和shmdt

秋风 2016-11-24