父进程创建两个子进程,子进程1执行 server(),子进程2执行client();client发送10 条类型为10~1的消息入队列,server接收消 息。 要求:client将键盘输入的字符作为消息正文 发送出去,server只接收消息类型为5~1的消 息并打印输出消息正文内容及消息类型号 要求:父进程在等待子进程结束后删除消息 队列。求完整代码
时间: 2024-03-16 16:45:15 浏览: 14
以下是基于Linux系统的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define MSG_TYPE1 10
#define MSG_TYPE2 9
struct msgbuf {
long mtype;
char mtext[1024];
};
int msgid;
void client() {
struct msgbuf msg;
char input[1024];
int i;
for (i = MSG_TYPE1; i >= MSG_TYPE2; i--) {
printf("Please enter a message to send (type %d):\n", i);
fgets(input, 1024, stdin);
msg.mtype = i;
strcpy(msg.mtext, input);
if (msgsnd(msgid, &msg, sizeof(msg.mtext), 0) == -1) {
perror("msgsnd");
exit(1);
}
}
}
void server() {
struct msgbuf msg;
while (1) {
if (msgrcv(msgid, &msg, sizeof(msg.mtext), MSG_TYPE2, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("Received message (type %ld): %s\n", msg.mtype, msg.mtext);
if (msg.mtype == MSG_TYPE1) {
break;
}
}
}
int main() {
pid_t pid1, pid2;
msgid = msgget(IPC_PRIVATE, 0600);
if (msgid == -1) {
perror("msgget");
exit(1);
}
pid1 = fork();
if (pid1 == -1) {
perror("fork");
exit(1);
} else if (pid1 == 0) {
server();
exit(0);
}
pid2 = fork();
if (pid2 == -1) {
perror("fork");
exit(1);
} else if (pid2 == 0) {
client();
exit(0);
}
waitpid(pid2, NULL, 0);
waitpid(pid1, NULL, 0);
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
```
这个程序创建了一个消息队列,然后使用两个子进程进行通信。其中,子进程1执行server()函数,子进程2执行client()函数。client()函数会往消息队列中发送10条消息,消息类型从10~1递减,每个消息的正文是从键盘输入的字符。server()函数会不断地接收消息,只处理类型为5~1的消息,打印出消息正文和消息类型号。父进程在等待子进程结束后,删除消息队列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)