目录
1、使用消息队列完成两个进程之间相互通信
//msgsnd.c
#include <myhead.h>
// 要发送的消息类型
struct msgbuf
{
long mtype;
char mtext[1024];
};
// 定义一个宏,为后面需要传入数据的大小
#define SIZE sizeof(struct msgbuf) - sizeof(long)
int main(int argc, char const *argv[])
{
// 1.创建出一个key值,用于产生消息队列
key_t key = ftok("/", 'k');
if (key == -1)
{
perror("ftok error");
return -1;
}
// 2.通过生成的key创建出一个消息队列对象
int msqid = msgget(key, IPC_CREAT | 0664);
if (msqid == -1)
{
perror("msqid error");
return -1;
}
// 向消息队列中存放消息
struct msgbuf buf;
// 创建父子进程
int pid = fork();
if (pid < 0)
{
perror("fork error");
return -1;
}
else if (pid == 0)
{
// 子进程,用于读取消息队列中类型为2的数据
while (1)
{
// 读取消息队列中类型为1的数据
msgrcv(msqid, &buf, SIZE, 2, 0);
if (strcmp(buf.mtext, "quit") == 0)
{
break;
}
// 直接输出到终端,读到了什么内容
printf("\n接收到的数据为:%s\n", buf.mtext);
}
}
//