编写一个程序message.c,在其中由父进程建立一个消息队列,然后由新建立的子进程在表明身份后,向消息队列中写如下列信息: Hi,this is child process sending message!。父进程在等待子进程对消息队列写操作完成后,从中读取信息,并显示出来,在删除消息队列后结束程序。
时间: 2024-03-25 16:38:44 浏览: 16
好的,下面是 `message.c` 的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <sys/wait.h>
#define MSG_SIZE 256
struct msgbuf {
long mtype;
char mtext[MSG_SIZE];
};
int main() {
pid_t pid;
int msgid;
struct msgbuf msg;
key_t key;
// 生成消息队列键值
if ((key = ftok(".", 'a')) == -1) {
perror("ftok error");
exit(1);
}
// 创建消息队列
if ((msgid = msgget(key, IPC_CREAT|0666)) == -1) {
perror("msgget error");
exit(1);
}
// 创建子进程
if ((pid = fork()) == -1) {
perror("fork error");
exit(1);
} else if (pid == 0) { // 子进程
// 发送消息
msg.mtype = 1;
sprintf(msg.mtext, "Hi, this is child process %d sending message!", getpid());
if (msgsnd(msgid, &msg, strlen(msg.mtext)+1, 0) == -1) {
perror("msgsnd error");
exit(1);
}
exit(0);
} else { // 父进程
// 等待子进程发送消息
waitpid(pid, NULL, 0);
// 接收消息
if (msgrcv(msgid, &msg, MSG_SIZE, 1, 0) == -1) {
perror("msgrcv error");
exit(1);
}
printf("%s\n", msg.mtext);
// 删除消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl error");
exit(1);
}
}
return 0;
}
```
程序运行后,父进程会创建一个消息队列,然后创建子进程并等待子进程发送消息。子进程发送消息后退出,父进程接收消息并显示,然后删除消息队列。最终程序退出。