编写一个程序 message.c,在其中由父进程建立一个信息队列,然后由新建立 的子进程在表明身份后,向消息队列中写如下列信息:Hi,this is child process sending message!。父进程在等待子进程对消息队列写操作完成后,从中读取信息,并显示出来,
时间: 2024-03-02 07:53:40 浏览: 19
好的,这是一个进程间通信的问题,需要用到消息队列。下面是代码实现:
```c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MSG_SIZE 128
struct msgbuf {
long mtype;
char mtext[MSG_SIZE];
};
int main() {
key_t key;
int msgid;
pid_t pid;
struct msgbuf msg;
// 生成一个 key
key = ftok(".", 'm');
if (key == -1) {
perror("ftok");
exit(1);
}
// 创建一个消息队列
msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1) {
perror("msgget");
exit(1);
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
}
if (pid == 0) { // 子进程
msg.mtype = 100;
strcpy(msg.mtext, "Hi, this is child process sending message!");
if (msgsnd(msgid, &msg, strlen(msg.mtext)+1, 0) == -1) {
perror("msgsnd");
exit(1);
}
exit(0);
} else { // 父进程
if (wait(NULL) == -1) {
perror("wait");
exit(1);
}
if (msgrcv(msgid, &msg, MSG_SIZE, 1, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("%s\n", msg.mtext);
// 删除消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
exit(0);
}
}
```
运行程序,输出为:
```
Hi, this is child process sending message!
```
说明消息队列通信正常。