天天看點

程序間通信:消息隊列通信方式

在學習LabVIEW時,深入的時候,學習到了隊列。當時書的作者是用這個圖形程式設計的語言和C/C++進行比較的,他說C/C++中有隊列,我很一臉茫然。舉例子都是舉得大家都知道的,但這個我确實沒聽說過,怎麼去比較嘛。

       不過今天是學習了,不過以後會不會學習LabVIEW了,我就是學習了這個消息隊列。其實LabVIEW不能用在ARM上,能用在就是工控之類的裸機上,沒有發揮其特點。

        記錄的東西不多,一個例子:

#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

struct msg_buf
{
	int mtype;
	char data[255];
	
};

int main()
{
	key_t key;
	int msgid;
	int ret;
	struct msg_buf msgbuf;
	
	key = ftok("/tmp/2", 'a');
	printf("key = [%x]\n", key);
	msgid = msgget(key, IPC_CREAT|0666);
	
	if(msgid == -1)
	{
		printf("create error\n");
		return -1;
	}
	
	msgbuf.mtype = getpid();
	strcpy(msgbuf.data, "test haha");
	ret = msgsnd(msgid, &msgbuf, sizeof(msgbuf.data), IPC_NOWAIT);
	if(ret == -1)
	{
		printf("send message err\n");
		return -1;
	}
	printf("recv_msg = [%s]\n", msgbuf.data);
	return 1;
}
           

運作結果:

[[email protected] Desktop]# ./a.out 
key = [ffffffff]
recv_msg = [test haha]
[[email protected] Desktop]#