《UNIX网络编程:卷2》P122:图6-26
--------------------------------------------
#include <stdio.h> #include <stdlib.h> #include <sys/msg.h> #include <sys/ipc.h> #include <string.h> #include <errno.h> #define MSG_R 0400 #define MSG_W 0200 #define SVMSG_MODE (MSG_R | MSG_W | MSG_R>>3 | MSG_R>>6) #define MAX_DATA 64 * 1024 #define MAX_NMESG 4096 #define MAX_NIDS 4096 int max_mesg; struct mymesg { long type; char data[MAX_DATA]; }mesg; int main(int argc, char *argv[]) { int i, j, msqid, qid[MAX_NIDS]; // 创建一个消息队列 if ((msqid = msgget(IPC_PRIVATE, SVMSG_MODE | IPC_CREAT)) < 0) { fprintf(stderr, "msgget error: %s\n", strerror(errno)); exit(1); } // 确定最大消息大小,从65536字节开始测试 mesg.type = 1; for (i = MAX_DATA; i > 0; i -= 128) { if (msgsnd(msqid, &mesg, i, 0) == 0) { fprintf(stderr, "maximum amount of data per message = %4d\n", i); max_mesg = i; break; } if (errno != EINVAL) // 无错时输出结果 fprintf(stderr, "msgsnd error for length %d\n", i); } if (i == 0) { fprintf(stderr, "i == 0\n"); exit(1); } msgctl(msqid, IPC_RMID, NULL); // 删除消息队列 // 确定一个队列中可放置多少不同大小的消息 mesg.type = 1; for (i = 8; i <= max_mesg; i *= 2) { // 消息大小 // 创建一个消息队列 if ((msqid = msgget(IPC_PRIVATE, SVMSG_MODE | IPC_CREAT)) < 0) { fprintf(stderr, "msgget error: %s\n", strerror(errno)); exit(1); } for (j = 0; j < MAX_NMESG; j++) { // 消息数 // 在指定消息队列中放置消息 if (msgsnd(msqid, &mesg, i, IPC_NOWAIT) != 0) { if (errno == EAGAIN) break; fprintf(stderr, "msgsnd error, i = %4d, j = %4d\n", j, i); break; } } printf("%4d %4d-byte message were placed noto queue, ", j, i); printf(" %4d bytes total\n", i * j); msgctl(msqid, IPC_RMID, NULL); // 删除消息队列 } // 确定同时可打开多少标识符 mesg.type = 1; for (i = 0; i <= MAX_NIDS; i++) { // 创建一个消息队列 if ((qid[i] = msgget(IPC_PRIVATE, SVMSG_MODE | IPC_CREAT)) == -1) { printf("%4d identifiers open at once\n", i); break; } } for (j = 0; j < i; j++) msgctl(qid[j], IPC_RMID, NULL); // 移出消息队列 exit(0); }
--------------------------------------------
本人的测试平台为:
$ uname -a Linux user 3.13.0-32-generic #57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
运行程序:
$ ./limits maximum amount of data per message = 8192 2048 8-byte message were placed noto queue, 16384 bytes total 1024 16-byte message were placed noto queue, 16384 bytes total 512 32-byte message were placed noto queue, 16384 bytes total 256 64-byte message were placed noto queue, 16384 bytes total 128 128-byte message were placed noto queue, 16384 bytes total 64 256-byte message were placed noto queue, 16384 bytes total 32 512-byte message were placed noto queue, 16384 bytes total 16 1024-byte message were placed noto queue, 16384 bytes total 8 2048-byte message were placed noto queue, 16384 bytes total 4 4096-byte message were placed noto queue, 16384 bytes total 2 8192-byte message were placed noto queue, 16384 bytes total 3997 identifiers open at once