send.c
#include <myhead.h>
struct msgbuf {
long mytype;
char mtext[1000];
};
int main()
{
key_t key = ftok("./", 65);
struct msgbuf message;
if(key==-1)
{
perror("ftok");
return -1;
}
int msgID = msgget(key, 0666 | IPC_CREAT);
if(msgID == -1)
{
perror("msgget");
exit(1);
}
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
exit(1);
}
else if (pid == 0)
{
printf("子进程启动,等待父进程发送消息...\n");
exit(0);
}
else
{
printf("父进程启动,开始发送消息...\n");
while(1)
{
printf("输入消息 (输入'exit'退出): ");
fgets(message.mtext, 1000, stdin);
message.mtext[strcspn(message.mtext, "\n")] = 0; // 移除换行符
message.mytype = 1;
if (msgsnd(msgID, &message, sizeof(message.mtext), 0) == -1) {
perror("msgsnd");
exit(1);
}
if (strcmp(message.mtext, "exit") == 0) {
break;
}
}
wait(NULL);
printf("父进程结束\n");
}
return 0;
}
rev.c
#include <myhead.h>
struct msgbuf {
long mytype;
char mtext[1000];
};
int main()
{
key_t key = ftok("./", 65);
struct msgbuf message;
if(key==-1)
{
perror("ftok");
return -1;
}
int msgID = msgget(key, 0666 | IPC_CREAT);
if(msgID == -1)
{
perror("msgget");
exit(1);
}
pid_t pid = fork();
if (pid < 0)
{
perror("fork");
exit(1);
}
else if (pid == 0)
{
printf("子进程启动,开始接收消息...\n");
while(1) {
if (msgrcv(msgID, &message, sizeof(message.mtext), 1, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("收到消息: %s\n", message.mtext);
if (strcmp(message.mtext, "exit") == 0) {
break;
}
}
printf("子进程结束\n");
exit(0); }
else
{
printf("父进程启动,等待子进程接收消息...\n");
wait(NULL);
if (msgctl(msgID, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
printf("父进程结束,消息队列已删除\n");
}
return 0;
}