C++ 多进程学习总结

C++多进程

进程间通信

消息队列

  • 消息队列:提供一个种进程间发送/接收数据块(常为结构体数据)的方法。

函数接口

  • ftok():获取消息队列键值
  • msgget():创建和访问消息队列
  • msgsnd():向消息队列发送数据
  • msgrcv():从消息队列接收数据
  • msgctl():设置消息队列属性

示例

hpp

#define MSG_PATHNAME	"/tmp"	//系统任意存在的路径名
#define MSG_PROJ		(234)	//1~255任一数字

typedef struct _msgSt {
	int msgType;
	char msgData[32];
} MsgSt;

class IpcMsg
{
public:
	IpcMsg() {};
	~IpcMsg() {};

	int msgInit(){
		/* 生成key值 */
		m_msgKey = ftok(MSG_PATHNAME, MSG_PROJ);
		if (-1 == m_msgKey) {
			cout << "ftok msgKey error" << endl;
			return -1;
		}

		/*建立消息队列*/
		m_msgId = msgget(m_msgKey, 0666 | IPC_CREAT);
		if (-1 == m_msgId) {
			cout << "msg creat error" << endl;
			return -1;
		}
		return 0;
	}

	int msgSend(char *msgBuf, int msgSize){
		int ret = msgsnd(m_msgId, msgBuf, msgSize, 0);
		if (ret < 0) {
			cout << "msgsnd error" << endl;
			return -1;
		}
		return 0;
	}

	int msgRecv(char *msgBuf, int msgSize) {
		int ret = msgrcv(m_msgId, msgBuf, msgSize, 0, 0);
		if (ret < 0) {
			cout << "msgrcv error" << endl;
			return -1;
		}
		return ret;
	}

	void msgDeinit() {
		msgctl(m_msgId, IPC_RMID, NULL);
	}
private:
	key_t m_msgKey = -1;
	int m_msgId = -1;
};

cpp

void custom_ipc_msg_process_task(char* argv[]){
	
	if (nullptr == argv[1]) {
		cout << "argv[1] is nullptr" << endl;
	}
	string cmd = argv[1];
	cout << "cmd: " << cmd << endl;

	IpcMsg ipcMsg;
	/* 初始化msg */
	int ret = ipcMsg.msgInit();
	if (ret < 0) {
		cout << "msgInit error" << endl;
		return ;
	}

	if (0 == cmd.compare("msgsnd")) {
		MsgSt msgBuf;

		while(1){
			memset(&msgBuf, 0, sizeof(msgBuf));
			msgBuf.msgType = 1;
			strncpy(msgBuf.msgData, "msg test", strlen("msg test"));
			int ret = ipcMsg.msgSend((char *) & msgBuf, (int)sizeof(msgBuf));
			if (ret < 0) {
				cout << "msgSend error" << endl;
			}
			else {
				cout << "msgSend ok :" << msgBuf.msgType <<", " <<msgBuf.msgData<< endl;
			}
			sleep(3);
		}
	}
	else if (0 == cmd.compare("msgrcv")) {
		char recvBuf[128];
		while (1) {
			memset(recvBuf, 0, sizeof(recvBuf));
			int ret = ipcMsg.msgRecv(recvBuf, sizeof(recvBuf));
			if (ret < 0) {
				cout << "msgrcv error" << endl;
			}
			else if(ret == sizeof(MsgSt)) {
				MsgSt *msgBuf = (MsgSt *)recvBuf;
				cout << "msgrcv: " << msgBuf->msgType<<", " <<msgBuf->msgData<< endl;
			}
			else{
				cout << "msgrcv size error" << endl;
			}
		}
	}
	else {
		cout << "invalid cmd" << endl;
	}

	/* 去初始化msg */
	ipcMsg.msgDeinit();
	return;
}

测试结果
在这里插入图片描述

你可能感兴趣的:(C/C++,c++)