2011-03-07 149 views
2

任何人都可以请帮我指出我的程序中有什么错误?消息队列:msgsnd失败:无效参数

由于提前, 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失败:无效的参数

回答

8

你不必在你的buf.mtext(15个字符)"This is a test message" 23个字符plust多了一个足够的空间(对于NUL终结者)。

我说有可能破坏你的类型,甚至一些其他堆栈上的一条信息的好机会(如msqidlengthkey)。

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

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

有:

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

,看它是否修复它。

或者,使mtext大到足以存储您要放入的数据。

+0

谢谢,它解决了:-) – kingsmasher1 2011-03-07 16:17:10