/*可能存在死锁状态:当客户端发送数据给服务器,
服务器回射消息时,消息队列被多个客户端同时发送的大量消息填满,
服务器无法回射,形成死锁
/* server.c */
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m)
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
#define MSGMAX 8192
//消息结构体,一方面大小需小于系统限制MSGMAX,另外需以long/int长整形开始
/*消息结构体*/
struct msgbuf{
long mtype;//占四个字节
char mtext[MSGMAX];
}
void echo_srv(int msgid)
{
int n;
struct msgbuf msg;
memset(&msg, 0, sizeof(msg));
while(1){
if((n=msgrcv(msgid, &msg, MSGMAX, 1, 0))<0)
{
ERR_EXIT("msgsnd");
}
int pid;
pid = *((int*)msg.mtext);//读取消息中的mtext的前四个字节
fputs(msg.mtext+4, stdout);//前四个字节为类型号,只打印后面的消息
msg.mtype = pid;//将进程号作为消息类型号
msgsnd(msgid, &msg, n, 0);
memset(&msg, 0, sizeof(msg));
}
}
int main(int argc, char* argv[])
{
int msgid;
msgid = msgget(1234, 0666 | IPC_CREAT);//由服务器创建消息队列
msgid = msgget(1234, 0);//0可以打开任何权限的消息队列,只打开不创建
if(msgid == -1)
{
ERR_EXIT("msgget");
}
printf("msgget success\n");
echo_srv(msgid);
return 0;
}
/*client.c*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define ERR_EXIT(m)
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
#define MSGMAX 8192
//消息结构体,一方面大小需小于系统限制MSGMAX,另外需以long/int长整形开始
/*消息结构体*/
struct msgbuf{
long mtype;//占四个字节
char mtext[MSGMAX];
}
void echo_cli(int msgid)
{
int n;
int pid;
pid = getpid();
struct msgbuf msg;
memset(&msg, 0, sizeof(msg));
*((int*)msg.mtext) = pid;//将自己的进程号写进要发送的字符中
msg.mtype =1;//将要发送的消息类型为服务器1
while(fgets(msg.mtext, MSGMAX, stdin) != NULL)
{
if(msgsnd(msgsnd, &msg, 4+strlen(msg.mtext+4), 0)<0)
ERR_EXIT("msgsnd");
memset(msg.mtext+4, 0, MSGMAX-4);
if((n=msgrcv(msgid, &msg, MSGMAX, pid, 0))<0)//要接受的信息类型号为自己的进程号
{
ERR_EXIT("msgsnd");
}
fputs(msg.mtext+4, stdout);
memset(msg.mtext+4, 0,MSGMAX-4);
}
}
int main(int argc, char* argv[])
{
int msgid;
msgid = msgget(1234, 0);//0可以打开任何权限的消息队列,只打开不创建
if(msgid == -1)
{
ERR_EXIT("msgget");
}
printf("msgget success\n");
echo_cli(msgid);
return 0;
}
system v消息队列实现回射客户/服务器
最新推荐文章于 2020-11-25 10:37:01 发布