初始化消息队列

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

初始化消息队列

static int init_msq_master(char *ipcpath, int clean)
{
	struct msg_buf msg;
	int msqid = -1, ipckey = -1;
	int ret = -1;
	int msglen = 4096;

	/* 为建立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;
	}
	// 获取队列的key
	ipckey = ftok(ipcpath, 1);
	if (ipckey < 0) {
		printf("ftok for msq error! [err=%d]\n", errno);
		return -2;
	}
	
//如不关心消息队列中残留消息,可直接删除该消息队列。暂不删除
#if 0
	msgid = msgget(ftok(ipcpath, 1), 0666);
	if (msgid >= 0) {
		msgctl(msgid, IPC_RMID, NULL);
	}
#endif
	
	msqid = msgget(ipckey, IPC_CREAT|0666);
	if (msqid < 0) {
		int err = errno;
		printf("Create IPC queue error! [err=%d]\n", err);
		return -3;
	}
	if(clean){
		int cn = 0; //clean msg number
		//如果消息队列不为空,清空队列
		while (msgrcv(msqid, &msg, msglen, 0, IPC_NOWAIT) > 0) {
			printf("msglen=%d, mtype=%ld\n", msglen, msg.mtype);
			cn++;
			continue;
		}
		printf("msglen=%d, %d msg has been clean.\n", msglen, cn);
	}
	printf("msqid = %d\n", msqid);
	return msqid;
}