使用消息队列来解决这个问题。具体示例代码如下:
创建消息队列:
#include
#include
#include
// 创建消息队列
int create_msg_queue(key_t key)
{
int mq_id;
// 创建消息队列,IPC_CREAT表示如果队列不存在就创建它
mq_id = msgget(key, IPC_CREAT | 0666);
if (mq_id == -1) {
perror("msgget error");
return -1;
}
return mq_id;
}
向消息队列中发送消息:
#include
// 定义消息数据结构
struct my_msgbuf {
long mtype; // 消息类型
char mtext[128]; // 消息内容
};
// 发送消息
void send_msg(int mq_id, long mtype, char *msg)
{
int ret;
struct my_msgbuf buf;
buf.mtype = mtype;
strcpy(buf.mtext, msg);
ret = msgsnd(mq_id, &buf, sizeof(buf.mtext), 0);
if (ret == -1) {
perror("msgsnd error");
exit(EXIT_FAILURE);
}
}
从消息队列中接收消息:
#include
// 接收消息
void recv_msg(int mq_id, long mtype, char *msg)
{
int ret;
struct my_msgbuf buf;
ret = msgrcv(mq_id, &buf, sizeof(buf.mtext), mtype, 0);
if (ret == -1) {
perror("msgrcv error");
exit(EXIT_FAILURE);
}
strcpy(msg, buf.mtext);
}
使用消息队列解决不同进程等待不同类型的消息问题的关键就是在发送和接收消息时指定消息类型,并且在创建消息队列时为每种类型的消息指定一个唯一的类型。这样不同进程只需要向同一个消息队列中发送或接收指定类型的消息即可。
上一篇:不同激活函数的性能比较