當我運行以下程序時,我總是出現錯誤消息「Message too long」。爲什麼?mqueue:消息太長
這是源:
#define NAME "/q"
#define SIZE 16
void main()
{
mqd_t mq;
char buffer[SIZE+1];
struct mq_attr attr;
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = SIZE;
attr.mq_curmsgs = 0;
mq = mq_open(NAME, O_CREAT | O_RDWR, 0644, &attr);
printf ("opening mqueue: %s\n", strerror(errno));
mq_receive(mq, buffer, strlen(buffer), NULL);
printf ("receiving: %s\n", strerror(errno));
printf ("message: %s\n", buffer);
unlink(NAME);
}
這是outupt:
opening mqueue: Success
receiving: Message too long
message:
/** 新編輯 **/
奧科克我改變的代碼更好地消除一些模糊性
#define NAME "/q"
#define SIZE 1024
int main()
{
mqd_t mq;
char buffer[SIZE+1] = {0};
struct mq_attr attr = {0};
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = SIZE;
attr.mq_curmsgs = 0;
if ((mqd_t) -1 == (mq = mq_open(NAME, O_CREAT | O_RDWR, 0644, &attr)))
printf("opening mqueue: %s\n", strerror(errno));
if (-1 == mq_receive(mq, buffer, SIZE+1, NULL))
printf("receiving: %s\n", strerror(errno));
printf("message: %s\n", buffer);
if (-1 == unlink(NAME))
perror("unlink() failed");
return 0;
}
輸出
receiving: Message too long
message:
unlink() failed: No such file or directory
除非你知道發生錯誤,你不應該檢查'errno'。測試'mq_receive'返回值。 – ugoren
它是-1所以,有一個錯誤:( –
你希望收到什麼消息?也許它是非常大的?試圖提供更完整的數據。 – ugoren