输出用消息队列和共享存储实现的可运行的代码
时间: 2024-02-06 12:09:46 浏览: 24
以下是一个简单的示例代码,使用消息队列和共享内存实现进程间通信:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#define MSG_KEY 1234
#define SHM_KEY 5678
#define MSG_SIZE 1024
typedef struct {
long type;
char text[MSG_SIZE];
} message;
int main() {
int msgid, shmid;
message msg;
char *shm;
key_t key = MSG_KEY;
// 创建消息队列
if ((msgid = msgget(key, IPC_CREAT | 0666)) == -1) {
perror("msgget");
exit(1);
}
key = SHM_KEY;
// 创建共享内存
if ((shmid = shmget(key, MSG_SIZE, IPC_CREAT | 0666)) == -1) {
perror("shmget");
exit(1);
}
// 将共享内存附加到当前进程的地址空间中
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
while (1) {
printf("Enter message: ");
fgets(msg.text, MSG_SIZE, stdin);
// 向消息队列发送消息
msg.type = 1;
if (msgsnd(msgid, &msg, strlen(msg.text) + 1, 0) == -1) {
perror("msgsnd");
exit(1);
}
// 将消息写入共享内存
strncpy(shm, msg.text, MSG_SIZE);
// 从共享内存读取消息
printf("Received message: %s", shm);
}
// 分离共享内存
if (shmdt(shm) == -1) {
perror("shmdt");
exit(1);
}
// 删除共享内存
if (shmctl(shmid, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(1);
}
// 删除消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
```
在本示例代码中,我们创建了一个消息队列和一个共享内存,然后使用 `msgsnd()` 向消息队列发送消息,使用 `strncpy()` 将消息写入共享内存,最后使用 `shmdt()` 分离共享内存并使用 `shmctl()` 删除共享内存,使用 `msgctl()` 删除消息队列。
请注意,此示例代码仅用于说明如何使用消息队列和共享内存实现进程间通信。实际应用中,还需要考虑更多的细节,例如如何处理多个进程同时访问共享内存的情况,如何处理消息队列满的情况等。