使用消息队列的IPC

先决条件: 进程间通信 消息队列是存储在内核中并由消息队列标识符标识的消息的链表。将创建一个新队列或由打开一个现有队列 msgget() . 新消息通过以下方式添加到队列末尾: msgsnd() 。每条消息都有一个正长整型字段、一个非负长度和实际数据字节(对应于长度),当消息添加到队列时,所有这些字节都会指定给msgsnd()。消息是通过 msgrcv() .我们不必按先进先出的顺序获取消息。相反,我们可以根据消息的类型字段获取消息。 所有进程都可以通过访问公共系统消息队列来交换信息。发送进程(通过某些(操作系统)消息传递模块)将消息放入另一个进程可以读取的队列。每个消息都有一个标识或类型,以便流程可以选择适当的消息。为了首先获得对队列的访问权,进程必须共享一个公共密钥。

null

图片[1]-使用消息队列的IPC-yiteyi-C++库

用于消息队列的系统调用:

  • ftok() :用于生成唯一密钥。
  • msgget() :返回新创建的消息队列的消息队列标识符,或返回具有相同键值的队列的标识符。
  • msgsnd() :通过调用msgsnd()将数据放入消息队列。
  • msgrcv() :从队列中检索消息。
  • msgctl() :它对队列执行各种操作。通常,它用于销毁消息队列。

写入进程的消息队列

C

// C Program for Message Queue (Writer Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX 10
// structure for message queue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok( "progfile" , 65);
// msgget creates a message queue
// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
message.mesg_type = 1;
printf ( "Write Data : " );
fgets (message.mesg_text,MAX,stdin);
// msgsnd to send message
msgsnd(msgid, &message, sizeof (message), 0);
// display the message
printf ( "Data send is : %s " , message.mesg_text);
return 0;
}


读卡器进程的消息队列

C

// C Program for Message Queue (Reader Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
// structure for message queue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
// ftok to generate unique key
key = ftok( "progfile" , 65);
// msgget creates a message queue
// and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
// msgrcv to receive message
msgrcv(msgid, &message, sizeof (message), 1, 0);
// display the message
printf ( "Data Received is : %s " ,
message.mesg_text);
// to destroy the message queue
msgctl(msgid, IPC_RMID, NULL);
return 0;
}


输出:

图片[2]-使用消息队列的IPC-yiteyi-C++库

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享