cat /proc/sys/kernel/msgmax最大消息长度限制
cat /proc/sys/kernel/msgmnb消息队列总的字节数
cat /proc/sys/kernel/msgmni消息条目数
消息队列综合案例
//server #include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> #define ERR_EXIT(m) \
do \
{ \
perror(m); \
} \
while(0); struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[1024]; /* message data */
}; int main()
{
struct msgbuf revbuf;
int key = 0;
int msgid = 0;
int ret = 0;
int pid = 0; key = ftok("./", '2');
if (key < 0)
ERR_EXIT("ftok"); //获取消息队列
ret = msgget(key, 0666 | IPC_CREAT | IPC_EXCL);
if (ret < 0)
{
if (errno == EEXIST) //如果消息队列已存在
msgid = msgget(key, 0666);
else
ERR_EXIT("msgget:");
}
else
msgid = ret; //设置发送buf
memset(&revbuf, 0, sizeof(revbuf)); revbuf.mtype = 1; //接收方总是接收类型1
while (1)
{
ret = msgrcv(msgid, &revbuf, sizeof(revbuf.mtext), 1, 0);
if (ret < 0)
ERR_EXIT("msgrcv:"); fputs(revbuf.mtext + 4, stdout); pid = *((int *)(revbuf.mtext)); revbuf.mtype = pid;
ret = msgsnd(msgid, &revbuf, ret, IPC_NOWAIT);
if (ret < 0)
ERR_EXIT("msgsnd");
} return 0;
}
//clt #include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h> #define ERR_EXIT(m) \
do \
{ \
perror(m); \
} \
while(0); struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[1024]; /* message data */
}; int main()
{
struct msgbuf sndbuf;
struct msgbuf revbuf;
int key = 0;
int msgid = 0;
int ret = 0;
int pid = 0; key = ftok("./", '2');
if (key < 0)
ERR_EXIT("ftok"); //获取消息队列
ret = msgget(key, 0666 | IPC_CREAT | IPC_EXCL);
if (ret < 0)
{
if (errno == EEXIST) //如果消息队列已存在
msgid = msgget(key, 0666);
else
ERR_EXIT("msgget:");
}
else
msgid = ret; //设置发送buf
memset(&sndbuf, 0, sizeof(sndbuf));
memset(&revbuf, 0, sizeof(revbuf)); pid = getpid(); //获取pid作为包头发出去 while (fgets(sndbuf.mtext + 4, sizeof(sndbuf.mtext), stdin) != NULL)
{
sndbuf.mtype = 1; //发送方总是发送类型1 memcpy(sndbuf.mtext, &pid, 4);
//*((int*)sndbuf.mtext) = pid; //这句话是指将sndbuf.mtext最前面四个字节指向一个int类型指针 ret = msgsnd(msgid, &sndbuf, strlen(sndbuf.mtext + 4) + 4, IPC_NOWAIT);
if (ret < 0)
ERR_EXIT("msgsnd"); sleep(1);
//读取
ret = msgrcv(msgid, &revbuf, sizeof(revbuf.mtext), pid, IPC_NOWAIT);
if (ret < 0)
ERR_EXIT("msgrcv:"); fputs(revbuf.mtext + 4, stdout); memset(&sndbuf, 0, sizeof(sndbuf));
memset(&revbuf, 0, sizeof(revbuf));
}
return 0;
}