linux 消息队列的发送和接收程序的编写
时间: 2024-05-13 15:15:39 浏览: 7
Linux 消息队列是一种进程间通信方式,可以实现不同进程之间的数据传输。下面是消息队列的发送和接收程序的编写实例:
发送程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/msg.h>
struct message
{
long mtype;
char mtext[256];
};
int main()
{
int msqid;
key_t key;
struct message msg;
// 创建消息队列
key = ftok(".", 'a');
msqid = msgget(key, 0666 | IPC_CREAT);
if (msqid == -1)
{
perror("msgget");
exit(1);
}
// 设置消息类型
msg.mtype = 1;
// 输入消息内容
printf("Enter message: ");
fgets(msg.mtext, sizeof(msg.mtext), stdin);
// 发送消息
if (msgsnd(msqid, &msg, sizeof(msg.mtext), 0) == -1)
{
perror("msgsnd");
exit(1);
}
printf("Message sent: %s\n", msg.mtext);
return 0;
}
```
接收程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/msg.h>
struct message
{
long mtype;
char mtext[256];
};
int main()
{
int msqid;
key_t key;
struct message msg;
// 打开消息队列
key = ftok(".", 'a');
msqid = msgget(key, 0666 | IPC_CREAT);
if (msqid == -1)
{
perror("msgget");
exit(1);
}
// 接收消息
if (msgrcv(msqid, &msg, sizeof(msg.mtext), 1, 0) == -1)
{
perror("msgrcv");
exit(1);
}
printf("Message received: %s\n", msg.mtext);
// 关闭消息队列
if (msgctl(msqid, IPC_RMID, NULL) == -1)
{
perror("msgctl");
exit(1);
}
return 0;
}
```
以上代码中,发送程序先创建一个消息队列,并设置消息类型为1。然后输入消息内容,并通过 msgsnd 函数发送消息到消息队列中。
接收程序打开同样的消息队列,并通过 msgrcv 函数接收类型为1的消息。接收完消息后,通过 msgctl 函数关闭消息队列。
注意:以上代码中的错误处理部分并不完整,仅供参考。实际应用中应该根据具体情况进行完善。