linux下写一个ipc订阅端的进程程序,接收来自发送端的数据
时间: 2024-03-06 11:47:41 浏览: 18
在Linux下,可以使用System V IPC机制中的消息队列来实现IPC订阅端的进程程序。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSG_SIZE 1024
typedef struct {
long mtype;
char mtext[MSG_SIZE];
} MsgBuf;
int main(int argc, char *argv[]) {
key_t key;
int msgid;
MsgBuf msgbuf;
// 生成key
if ((key = ftok(".", 'a')) == -1) {
perror("ftok error");
exit(1);
}
// 创建/获取消息队列
if ((msgid = msgget(key, IPC_CREAT | 0666)) == -1) {
perror("msgget error");
exit(1);
}
// 接收消息
while (1) {
if (msgrcv(msgid, &msgbuf, MSG_SIZE, 0, 0) == -1) {
perror("msgrcv error");
exit(1);
}
printf("Received message: %s\n", msgbuf.mtext);
}
return 0;
}
```
在上面的代码中,我们使用ftok函数生成一个key,然后使用msgget函数创建或获取消息队列。接着,我们使用msgrcv函数不断地接收来自发送端的消息,直到程序被手动终止。
需要注意的是,这里我们使用了一个名为MsgBuf的结构体来封装消息内容,其包含一个长整型mtype和一个字符数组mtext。其中,mtype通常用于区分不同的消息类型,这里我们设置为0表示接收所有类型的消息。