创建共享内存

大耗子 2020年08月19日 98次浏览

创建共享内存

//创建共享内存
int init_shmget_master(char* ipcpath, unsigned int shm_size)
{
	int ret = -1, ipckey = -1;
	struct shmid_ds shm_stat;
	void *shm = NULL;
	
	/* 为建立IPC通讯准备key值。注意:
		1、使用ftok时,文件必须存在;
		2、要想确保每次获得key值不变,文件不能被删除;
		3、第2个参数表示子序号,只能为8bits(1-255,must be non-zero)
	*/
	// 判断文件是否存在
	if ((stat(ipcpath,&buf))==-1) {
		printf("file is not exist\n");
		return -1;
	}
	ipckey = ftok(ipcpath, 1);
	if (ipckey < 0) {
		printf("ftok for shm error! [err=%d]\n", errno);
		return -2;
	} 
	
	//如果共享内存已存在,则检查共享内存大小,大小不符则重建
	shmid = shmget(ipckey, 0, 0); //获取共享内存标识符
	if (shmid >= 0) {
		memset(&shm_stat, 0, sizeof(shm_stat));
		shmctl(shmid, IPC_STAT, &shm_stat);
		if (shm_stat.shm_segsz == shm_size) {
			goto SHMGET_OK;
		}
		printf("old-shm[id:%d, size:%u], new-shm[size:%u], "
			"shm must be recreate!\n", shmid, (__u32)shm_stat.shm_segsz, shm_size);
		shmctl(shmid, IPC_RMID, NULL);
	}

	
	//创建共享内存
	shmid = shmget(ipckey, shm_size, IPC_CREAT|0666);
	if (shmid < 0) {
		printf("Create share memory error! [err=%d]\n", errno);
		printf("====ipckey:%08x, shm_length:%d\n", ipckey, shm_size);
		return -1;
	}
	
SHMGET_OK:
	printf("shmget success! shmid:%d, size:%d, ipckey:%08x\n",
		shmid, shm_size, ipckey);
	return shmid;
}