【问题标题】:Message queue: msgsnd failed : Invalid argument消息队列:msgsnd 失败:参数无效
【发布时间】:2011-07-10 05:57:02
【问题描述】:

谁能帮我指出我的程序中的错误是什么?

提前致谢, kingsmasher1

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>

typedef struct msgbuf {
    long mtype;     /* message type, must be > 0 */
    char mtext[15];  /* message data */
} msgbuf;

int main() {
    key_t key;
    int msqid, pid, length;
    msgbuf buf;

    msqid=msgget(IPC_PRIVATE,IPC_CREAT);

    if(msqid==-1){
        perror("msgget failed");
        return;
    }
    else {
        printf("msgget succeeded. ID:%u",msqid);
    }

    pid=fork();

    if(pid==-1) {
        perror("fork failed\n");
    }

    buf.mtype=1;
    strcpy(buf.mtext, "This is a test message");
    length=sizeof(buf.mtext);

    if(msgsnd(msqid,&buf,length,0)!=0) {
        perror("msgsnd failed:\n");
    }
    else {
       printf("msgsnd succeeded\n");
    }
}

输出: msgsnd 失败:参数无效

【问题讨论】:

    标签: c linux message-queue


    【解决方案1】:

    buf.mtext(15 个字符)中没有足够的空间用于 "This is a test message"(23 个字符加上一个用于 NUL 终止符)。

    我想说很有可能会损坏您的类型,甚至是堆栈上的某些其他信息(例如msqidlengthkey)。

    无论这是否是实际问题,它仍然是未定义的行为,应该予以修复。我要做的第一件事是通过替换来检查:

    strcpy(buf.mtext, "This is a test message");
    

    与:

    strcpy(buf.mtext, "XYZZY");  // 5 plus the NUL
    

    看看它是否修复它。

    或者,使mtext 足够大以存储您放入其中的数据。

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      • 2011-02-21
      • 2014-06-23
      • 2014-05-28
      相关资源
      最近更新 更多