我剛剛學習如何使用消息隊列,並且我遇到了一些困難。我使用兩個完全獨立的應用程序來進行測試 - 一個是「發件人」,另一個是「接收器」。需要爲OpenWRT中的IPC消息隊列增加緩衝區
當我運行發件人時,它發送15個字符串到管道,但隨後失敗,出現「資源暫時不可用」錯誤。我只需要在接收端使用消息,但爲什麼只有15條消息?我可能會發送很多消息,所以我想將它增加到一個更大的數字,例如1000左右。
我試圖設置消息隊列的大小爲32767,所以我至少期待31,但顯然msg_qbytes
是不相關的可以緩衝的消息數量。
發送者的代碼如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#define MESSAGE_SIZE 1024
typedef struct msgbuf
{
long mtype;
char mtext[MESSAGE_SIZE];
};
int main(int argc, char *argv[]) {
int msgid;
int ret;
struct msqid_ds msg_settings;
long key;
struct msgbuf msg;
key = strtol(argv[1], NULL, 10);
// print the message queue ID for reading via msgrcv
printf("Getting message queue with key = %ld\n", key);
usleep(1000000);
msgid = msgget((key_t)key, 0666 | IPC_CREAT);
if (msgid == -1) {
perror("msgget failed with error");
exit(EXIT_FAILURE);
}
// read in current queue settings and then set the new
// queue size.
ret = msgctl(msgid, IPC_STAT, &msg_settings);
msg_settings.msg_qbytes = 32767;
msgctl(msgid, IPC_SET, &msg_settings);
while(1) {
msg.mtype = 1; // we'll always leave this as 1
memset(&(msg.mtext), 0, MESSAGE_SIZE);
sprintf(msg.mtext, "hi");
printf("Sending data: %s\n", msg.mtext);
ret = msgsnd(1, &msg, MESSAGE_SIZE, IPC_NOWAIT);
usleep(500000);
if(ret == -1) {
perror("msgsnd failed\n");
}
printf("leaving...\n");
return EXIT_SUCCESS;
}
接收器的代碼如下所示:
,我已經解決了原來的問題#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#define MESSAGE_SIZE 1024
typedef struct msgbuf
{
long mtype;
char mtext[MESSAGE_SIZE];
};
int main(int argc, char *argv[]) {
long int msgtyp = 1;
int ret;
size_t msgsz;
struct msgbuf mymsg;
int msgid;
msgid = strtol(argv[1], NULL, 10);
printf("Reading message queue with ID = %d\n", msgid);
usleep(1000000);
while(1) {
msgsz = (size_t)MESSAGE_SIZE;
ret = msgrcv(msgid, &mymsg, msgsz, msgtyp, IPC_NOWAIT);
if(ret == ENOMSG) {
usleep(100000);
continue;
}
if(ret == -1) {
perror("msgrcv failed");
} else {
printf("Read data: %s", mymsg.mtext);
}
usleep(100000);
}
return EXIT_SUCCESS;
}
我看到過類似的信息,並試圖從OpenWRT查詢當前值,但似乎沒有以這種方式配置。 – Dave