linux设计程序实现功能:1.设计两个独立进程,即发送进程和接收进程,通过消息队列进行进程通信,以“end”作为结束消息
时间: 2024-02-07 10:03:28 浏览: 30
好的,我可以为您提供一份简单的 Linux 程序实现,满足您的要求。以下是程序代码:
发送进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/msg.h>
#define MAX_MSG_SIZE 1024
struct message {
long type;
char text[MAX_MSG_SIZE];
};
int main() {
int msgid;
struct message msg;
// 创建消息队列
msgid = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
if (msgid == -1) {
perror("msgget error");
exit(EXIT_FAILURE);
}
// 发送消息
while (1) {
printf("Enter message: ");
fgets(msg.text, MAX_MSG_SIZE, stdin);
msg.type = 1;
msgsnd(msgid, &msg, strlen(msg.text) + 1, 0);
if (strcmp(msg.text, "end\n") == 0) {
break;
}
}
// 删除消息队列
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
```
接收进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/msg.h>
#define MAX_MSG_SIZE 1024
struct message {
long type;
char text[MAX_MSG_SIZE];
};
int main() {
int msgid;
struct message msg;
// 获取消息队列
msgid = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
if (msgid == -1) {
perror("msgget error");
exit(EXIT_FAILURE);
}
// 接收消息
while (1) {
msgrcv(msgid, &msg, MAX_MSG_SIZE, 1, 0);
printf("Received message: %s", msg.text);
if (strcmp(msg.text, "end\n") == 0) {
break;
}
}
// 删除消息队列
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
```
这两个进程使用了 `msgget`、`msgsnd` 和 `msgrcv` 函数来进行进程间通信,并且在接收到消息为 "end" 时退出。您可以将以上代码分别保存到 send.c 和 recv.c 文件中,使用以下命令编译并运行程序:
```
gcc -o send send.c
gcc -o recv recv.c
./send | ./recv
```
这里使用管道将发送进程和接收进程连接起来,使它们能够相互通信。