#include "sys/types.h"
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>
struct msgbuf
{
long type;
char mtext[128];
char ID[4];
};
int main()
{
int msgid;
struct msgbuf buf;
msgid=msgget(IPC_PRIVATE,0777);
if(msgid<0)
{
printf("create mssage queue failure\n");
return -1;
}
buf.type=100;
printf("create message success msgid:%d",msgid);
system("ipcs -q");
fgets(buf.mtext,128,stdin);
msgsnd(msgid,(void *)&buf,strlen(buf.mtext),0);
while (1) ;
msgctl(msgid,IPC_RMID,NULL);
system("ipcs -q");
}
消息队列读完结点就被删除
步骤总结 msgget 在内核中创建消息队列 链式队列
mmgctl 删除 消息队列 修改内核空间属性
mmgsnd 用户空间数据写入消息队列
mmgrcv 用户空间可以读取到内核空间的消息队列
阻塞方式 非阻塞方式
A B 无亲缘关系的两个进程 通过消息队列进行通信 两个消息队列 全双工通信
管道通信 共享内存通信的区别和缺点
消息队列双向通信代码如下
服务器 :
#include "sys/types.h"
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>
struct msgbuf
{
long type;
char mtext[128];
char ID[4];
};
int main()
{
int msgid;
int pid;
int recvlen;
struct msgbuf buf ,recvbuf;
int key;
key =ftok("./a.c",'a');
if(key<0){
printf("create key failure\n");
return -1;
}
msgid=msgget(key,IPC_CREAT |0777);
if(msgid<0)
{
printf("create mssage queue failure\n");
return -1;
}
printf("create message success msgid:%d\n",msgid);
system("ipcs -q");
buf.type=100;
pid=fork();
if(pid <0)printf("fork failure\n");
if(pid >0){
while(1)
{
memset(buf.mtext,0,128);
printf("please input messsage:\n");
fgets(buf.mtext,128,stdin);
msgsnd(msgid,(void *)&buf,strlen(buf.mtext),0);
}
}
if(pid ==0)
{
while(1)
{
memset(recvbuf.mtext,0,128);
recvlen= msgrcv(msgid,(void *)&recvbuf,128,200,0);
printf("read data: %s\n",recvbuf.mtext);
printf("recvlen:%d\n",recvlen);
}
}
msgctl(msgid,IPC_RMID,NULL);
system("ipcs -q");
}
客户端
#include "sys/types.h"
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>
struct msgbuf
{
long type;
char mtext[128];
char ID[4];
};
int main()
{
int msgid;
int recvlen;
int pid;
struct msgbuf buf ,recvbuf;
int key;
key =ftok("./a.c",'a');
if(key<0){
printf("create key failure\n");
return -1;
}
msgid=msgget(key,0777);
if(msgid<0)
{
printf("create mssage queue failure\n");
return -1;
}
printf("create message success msgid:%d\n",msgid);
pid=fork();
buf.type=200;
if(pid <0)printf("fork failure\n");
if(pid>0){
while(1)
{
memset(recvbuf.mtext,0,128);
recvlen= msgrcv(msgid,(void *)&recvbuf,128,100,0);
printf("read data: %s\n",recvbuf.mtext);
printf("recvlen:%d\n",recvlen);}
}
if(pid ==0)
{
while(1){
memset(buf.mtext,0,128);
printf("please input messsage:\n");
fgets(buf.mtext,128,stdin);
msgsnd(msgid,(void *)&buf,strlen(buf.mtext),0);
}
}
msgctl(msgid,IPC_RMID,NULL);
system("ipcs -q");
}