使用消息队列完成两个进程间的通信
msgsnd.c
#include <myhead.h>
//要发送的消息类型
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define SIZE sizeof(strlen[msgbuf] - sizeof(long)) //定义正文大小
int main(int argc, char const *argv[])
{
//创建key值,用于生产消息队列
key_t key = ftok("/", 'k');
if (key == -1)
{
perror("ftok error");
return -1;
}
printf("key=%#x", key);
//通过key值创建一个消息队列
int msqid = msgget(key, IPC_CREAT | 0664);
if (msqid == -1)
{
perror("msgget error");
return -1;
}
printf("msqid=%d\n", msqid);
//向消息队列中存放消息
struct msgbuf buf;
//创建一个父子进程
pid_t pid = fork();
//父进程
if (pid > 0)
{
buf.mtype = 1; //将发出去的信号类型始终定为1
printf("你可以开始输入了!!!\n");
while (1)
{
fgets(buf.mtext, 1023, stdin);
buf.mtext[strlen(buf.mtext) - 1] = 0; //将换行换成'\0'
//将消息发送到消息队列中
msgsnd(msqid, &buf, 1023, 0);
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
}
else if (pid == 0) //子进程
{
while (1)
{
msgrcv(msqid, &buf, 1023, 2, 0);
//参数1:消息队列id号
//参数2:消息的起始地址
//参数3:消息正文大小
//参数4:消息类型
//参数5:表示阻塞读取消息
printf("对方:%s\n", buf.mtext);
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
//退出进程
_exit(EXIT_SUCCESS);
}
else
{
perror("fork error");
return -1;
}
//阻塞回收
wait(NULL);
//删除消息队列
if (msgctl(msqid, IPC_RMID, NULL) == -1)
{
perror("msgctl error");
return -1;
}
return 0;
}
msgcrv.c
#include <myhead.h>
//要发送的消息类型
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define SIZE sizeof(strlen[msgbuf] - sizeof(long)) //定义正文大小
int main(int argc, char const *argv[])
{
//创建key值,用于生产消息队列
key_t key = ftok("/", 'k');
if (key == -1)
{
perror("ftok error");
return -1;
}
printf("key=%#x", key);
//通过key值创建一个消息队列
int msqid = msgget(key, IPC_CREAT | 0664);
if (msqid == -1)
{
perror("msgget error");
return -1;
}
printf("msqid=%d\n", msqid);
//向消息队列中存放消息
struct msgbuf buf;
//创建一个父子进程
pid_t pid = fork();
//父进程
if (pid > 0)
{
while (1)
{
msgrcv(msqid, &buf, 1023, 1, 0);
//参数1:消息队列id号
//参数2:消息的起始地址
//参数3:消息正文大小
//参数4:消息类型
//参数5:表示阻塞读取消息
printf("对方:%s\n", buf.mtext);
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
}
else if (pid == 0) //子进程
{
buf.mtype = 2; //将发出去的信号类型始终定为1
printf("你可以开始输入了!!!\n");
while (1)
{
fgets(buf.mtext, 1023, stdin);
buf.mtext[strlen(buf.mtext) - 1] = 0; //将换行换成'\0'
//将消息发送到消息队列中
msgsnd(msqid, &buf, 1023, 0);
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
}
//退出进程
_exit(EXIT_SUCCESS);
}
else
{
perror("fork error");
return -1;
}
//非阻塞回收
wait(NULL);
//删除消息队列
if (msgctl(msqid, IPC_RMID, NULL) == -1)
{
perror("msgctl error");
return -1;
}
return 0;
}