linux 3个不同线程之间做msg通信
时间: 2023-05-25 20:03:22 浏览: 58
一个经典的Linux线程之间msg通信的示例代码如下:
Thread 1
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>
#define MSG_TYPE 1
typedef struct {
long type;
char text[1024];
} Msg_t;
int main()
{
key_t key;
int msgid;
Msg_t msg;
// 获取消息队列键值
if ((key = ftok(".", 'a')) == -1) {
perror("ftok");
exit(1);
}
// 创建或获取消息队列
if ((msgid = msgget(key, 0666 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
// 将消息发送到消息队列
strcpy(msg.text, "Hello from Thread 1.");
msg.type = MSG_TYPE;
if (msgsnd(msgid, (void *)&msg, sizeof(msg.text), 0) == -1) {
perror("msgsnd");
exit(1);
}
printf("Thread 1: Sent message to Thread 2.\n");
// 接收消息从消息队列
if (msgrcv(msgid, (void *)&msg, sizeof(msg.text), MSG_TYPE + 1, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("Thread 1: Received message from Thread 3: %s\n", msg.text);
// 删除消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
```
Thread 2
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>
#define MSG_TYPE 1
typedef struct {
long type;
char text[1024];
} Msg_t;
int main()
{
key_t key;
int msgid;
Msg_t msg;
// 获取消息队列键值
if ((key = ftok(".", 'a')) == -1) {
perror("ftok");
exit(1);
}
// 创建或获取消息队列
if ((msgid = msgget(key, 0666 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
// 接收消息从消息队列
if (msgrcv(msgid, (void *)&msg, sizeof(msg.text), MSG_TYPE, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("Thread 2: Received message from Thread 1: %s\n", msg.text);
// 将消息发送到消息队列
strcpy(msg.text, "Hello from Thread 2.");
msg.type = MSG_TYPE + 1;
if (msgsnd(msgid, (void *)&msg, sizeof(msg.text), 0) == -1) {
perror("msgsnd");
exit(1);
}
printf("Thread 2: Sent message to Thread 3.\n");
return 0;
}
```
Thread 3
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>
#define MSG_TYPE 1
typedef struct {
long type;
char text[1024];
} Msg_t;
int main()
{
key_t key;
int msgid;
Msg_t msg;
// 获取消息队列键值
if ((key = ftok(".", 'a')) == -1) {
perror("ftok");
exit(1);
}
// 创建或获取消息队列
if ((msgid = msgget(key, 0666 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
// 接收消息从消息队列
if (msgrcv(msgid, (void *)&msg, sizeof(msg.text), MSG_TYPE + 1, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("Thread 3: Received message from Thread 2: %s\n", msg.text);
// 将消息发送到消息队列
strcpy(msg.text, "Hello from Thread 3.");
msg.type = MSG_TYPE + 2;
if (msgsnd(msgid, (void *)&msg, sizeof(msg.text), 0) == -1) {
perror("msgsnd");
exit(1);
}
printf("Thread 3: Sent message to Thread 1.\n");
return 0;
}
```
上述代码通过消息队列实现了三个线程之间的通信。具体地,Thread 1发送消息到Thread 2,Thread 2接收消息,并发送消息到Thread 3,Thread 3接收消息,并发送消息到Thread 1。其中,消息的类型通过msg.type指定,消息的文字内容存储在msg.text中。您可以根据具体需求修改代码中的纯文本消息。