现在有两个进程,一个读进程,一个写进程。他们的职责如下:
- 写进程:创建消息队列,同时每隔1s向消息队列写入消息,消息类型为1。
- 读进程:每隔 1s 从消息队列中取出消息类型为 1 的消息
1、写进程实现
需要注意,msgsnd的第二个成员所使用的结构体需要自己声明,而且结构体的最后一个成员因为是数组,所以该素组也被称为“柔性数组”。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
struct msgbuf {
long mtype;
char mtext[1]; // 结构体最后一个成员如果是数组,这个数组被称为柔性数组
};
int main(){
key_t key = ftok(".", 100);
if(key < 0){
perror("ftok");
return 1;
}
int msgid = msgget(key, IPC_CREAT | IPC_EXCL | 0644);
if(msgid < 0)
{
perror("msgget");
return 1;
}
size_t msgsz = 128; // 柔性数组的大小
// 柔性数组所在结构体要动态分配内存
struct msgbuf* msgp = (struct msgbuf*)malloc(sizeof(struct msgbuf) + sizeof(char) * msgsz);
// 初始化结构体成员
msgp->mtype = 1; // 设置消息类型
const char* str = "hello, world!";
strcpy(msgp->mtext, str); // 将字符串拷贝到柔性数组里
while(1){
msgsnd(msgid, msgp, msgsz, 0);
sleep(1);
}
free(msgp);
msgp = NULL;
return 0;
}
可以在命令行输入 ipcs 来验证消息队列是否创建成功。
2、读进程实现
int main(){
key_t key = ftok(".", 100);
if(key < 0){
perror("ftok");
return 1;
}
int msgid = msgget(key, IPC_CREAT);
if(msgid < 0)
{
perror("msgget");
return 1;
}
struct msgbuf msgp;
while(1){
msgrcv(msgid, &msgp, 128, 1, 0);
printf("%s\n", msgp.mtext);
sleep(1);
}
return 0;
}