创建两个进程,使每个都能读写消息队列
代码:
msg_service.c
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct msgbuf
{
long mtype;
char mtest[128];
char ID[4];
};
int main()
{
struct msgbuf sendbuf,readbuf;
int msgid;
key_t key;
pid_t pid;
int readret;
key=ftok("b.c",5);
msgid = msgget(key,0755|IPC_CREAT);
if(msgid == -1)
{
printf("create message queue failed!\n");
return -1;
}
system("ipcs -q");
printf("create message queue success msgid =%d\n",msgid);
sendbuf.mtype=100;
pid=fork();
if(pid ==-1)
{
printf("fork fail\n");
return -1;
}
if(pid > 0)//父进程发送消息类型为100的消息给消息队列
{
while(1)
{
memset(sendbuf.mtest,0,128);
printf("please input to massage queue:\n");
fgets(sendbuf.mtest,128,stdin);
msgsnd(msgid,(void *)&sendbuf,strlen(sendbuf.mtest),0);
}
}
if(pid == 0)//子进程从消息队列中读取消息类型为100的消息
{
while(1)
{
memset(readbuf.mtest,0,128);
readret=msgrcv(msgid,(void *)&readbuf,128,99,0);
printf("receive byte form message queue is :%s\n",readbuf.mtest);
printf("total have %d byte\n",readret);
}
}
return 0;
}
代码:
msg_client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct msgbuf
{
long mtype;
char mtest[128];
char ID[4];
};
int main()
{
struct msgbuf sendbuf,readbuf;
int msgid;
key_t key;
pid_t pid;
int readret;
key=ftok("b.c",5);
msgid = msgget(key,0755|IPC_CREAT);
if(msgid == -1)
{
printf("create message queue failed!\n");
return -1;
}
system("ipcs -q");
printf("create message queue success msgid =%d\n",msgid);
sendbuf.mtype=99;
pid=fork();
if(pid ==-1)
{
printf("fork fail\n");
return -1;
}
if(pid == 0)//子进程发送消息类型为99的消息给消息队列
{
while(1)
{
//memset(sendbuf.mtest,0,128);
printf("please input to massage queue:\n");
fgets(sendbuf.mtest,128,stdin);
msgsnd(msgid,(void *)&sendbuf,strlen(sendbuf.mtest),0);
memset(sendbuf.mtest,0,128);
}
}
if(pid > 0)//父进程读取消息类型为100的消息
{
while(1)
{
memset(readbuf.mtest,0,128);
readret=msgrcv(msgid,(void *)&readbuf,128,100,0);
printf("receive byte form message queue is :%s\n",readbuf.mtest);
printf("total have %d byte\n",readret);
}
}
return 0;
}```
执行结果:
![请添加图片描述](https://img-blog.csdnimg.cn/65c4e9122a344698a4d6231e6b9d042d.png)
这时两个进程可进行通信。
程序执行流程: msgsnd(msgid,(void *)&sendbuf,strlen(sendbuf.mtest),0);中最后的参数0表示,当消息返送完才返回,所以没有消息发送时,进程会一直卡在这,msgrcv(msgid,(void *)&readbuf,128,100,0);中最后一个参数0表示,若无消息函数一直阻塞,所以没有读取到消息时,函数也会一直卡在这。