【C语言】消息队列

读取消息队列代码

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>

//int msgget(key_t key, int msgflg);
//ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
//                      int msgflg);



struct msgbuf{
   
        long mtype;       /* message type, must be > 0 */
        char mtext[128];    /* message data */
};


int main()
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言中,可以使用消息队列来实现进程间通信。消息队列是一种通信机制,用于在不同进程之间传输数据。它是一个消息的缓冲区域,进程可以将消息放入队列中,也可以从队列中获取消息。 以下是使用消息队列实现进程间通信的基本步骤: 1. 创建消息队列 使用系统调用msgget()创建一个消息队列。 2. 发送消息 使用系统调用msgsnd()发送消息到队列中。 3. 接收消息 使用系统调用msgrcv()从队列中接收消息。 4. 销毁消息队列 使用系统调用msgctl()销毁消息队列。 以下是一个示例代码,演示如何使用消息队列实现进程间通信: ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define MSG_SIZE 1024 struct msgbuf { long mtype; char mtext[MSG_SIZE]; }; int main() { int msgid; struct msgbuf msg; key_t key = ftok("msgqueue", 'a'); // 创建消息队列 msgid = msgget(key, IPC_CREAT | 0666); if (msgid == -1) { perror("msgget"); exit(1); } // 发送消息 msg.mtype = 1; sprintf(msg.mtext, "Hello, this is a message from process %d", getpid()); if (msgsnd(msgid, &msg, MSG_SIZE, 0) == -1) { perror("msgsnd"); exit(1); } // 接收消息 if (msgrcv(msgid, &msg, MSG_SIZE, 0, 0) == -1) { perror("msgrcv"); exit(1); } printf("Received message: %s\n", msg.mtext); // 销毁消息队列 if (msgctl(msgid, IPC_RMID, NULL) == -1) { perror("msgctl"); exit(1); } return 0; } ``` 在上面的示例代码中,首先使用ftok()函数将一个文件和一个字符转换为一个唯一的键值,然后使用msgget()函数创建一个消息队列。接下来,使用msgsnd()函数向消息队列发送一条消息,然后使用msgrcv()函数从消息队列中接收一条消息。最后,使用msgctl()函数销毁消息队列

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值