一个使用消息队列的demo
代码描述
- demo任务: 父进程fork得到子进程, 子进程往消息队列发送消息, 父进程从消息队列取消息
- 环境: ubuntu20.04, C++14
#include <sys/socket.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/msg.h>
#include <string.h>
#define BUFFER_SIZE 256
struct mymsg
{
long mtype;
char mtext[BUFFER_SIZE];
};
int main(int argc, char const *argv[])
{
int queid = msgget(IPC_PRIVATE, IPC_CREAT | IPC_EXCL);
pid_t pid = fork();
if (pid == 0)
{
mymsg child_buf;
child_buf.mtype = 1;
strcpy(child_buf.mtext, "hello world");
printf("child sent msg: %s\n", child_buf.mtext);
int ret = msgsnd(queid, &child_buf, strlen(child_buf.mtext), IPC_NOWAIT);
assert(ret != -1);
}
else
{
while (1)
{
mymsg msg_rcv;
int ret = msgrcv(queid, &msg_rcv, BUFFER_SIZE, 0, IPC_NOWAIT);
if (ret != -1)
{
printf("parent received msg: %s\n", msg_rcv.mtext);
break;
}
}
}
return 0;
}
运行结果
child sent msg: hello world
parent received msg: hello world