linux设计程序实现功能:1.设计两个独立进程,即发送进程和接收进程,通过消息队列进行进程通信,以“end”作为结束消息
时间: 2024-02-07 15:03:28 浏览: 28
很抱歉,我刚才的回答出现了重复,请允许我重新回答一下您的问题。
以下是一个实现了发送进程和接收进程之间通过消息队列进行进程通信的程序,以 "end" 作为结束消息:
发送进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_SIZE 256
struct message {
long type;
char data[MAX_SIZE];
};
int main() {
key_t key;
int msgid;
struct message msg;
// 创建消息队列
key = ftok(".", 'a');
msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1) {
perror("msgget error");
exit(EXIT_FAILURE);
}
// 发送消息
while (1) {
printf("Enter message: ");
fgets(msg.data, MAX_SIZE, stdin);
msg.type = 1;
msgsnd(msgid, &msg, strlen(msg.data) + 1, 0);
if (strcmp(msg.data, "end\n") == 0) {
break;
}
}
// 删除消息队列
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
```
接收进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_SIZE 256
struct message {
long type;
char data[MAX_SIZE];
};
int main() {
key_t key;
int msgid;
struct message msg;
// 获取消息队列
key = ftok(".", 'a');
msgid = msgget(key, 0666);
if (msgid == -1) {
perror("msgget error");
exit(EXIT_FAILURE);
}
// 接收消息
while (1) {
msgrcv(msgid, &msg, sizeof(msg.data), 1, 0);
printf("Received message: %s", msg.data);
if (strcmp(msg.data, "end\n") == 0) {
break;
}
}
return 0;
}
```
这两个进程使用了 `msgget`、`msgsnd` 和 `msgrcv` 函数来进行进程间通信,并且在接收到消息为 "end" 时退出。您可以将以上代码分别保存到 send.c 和 recv.c 文件中,使用以下命令编译并运行程序:
```
gcc -o send send.c
gcc -o recv recv.c
./send | ./recv
```
这里使用管道将发送进程和接收进程连接起来,使它们能够相互通信。