最近写个一个小程序 测试System V的消息队列工作机制,写完代码后编译通过但是运行出现这个错误msgsnd: Invalid argument
于是去Google ,可惜没有找到满意的结果,后来仔细检查代码发现 没有对消息类型赋值,花了我2个小时,终于搞定,以此告诫程序员要细心啊,呵呵
这是代码
/* 发送*/
#include
#include
#include
#include
#include
#include
#include
#define MAX_TEXT 512
struct my_msg_st
{
long my_msg_type; //消息类型
char msg_text[MAX_TEXT];
};
int main(int argc,char ** argv)
{
int running = 1;
struct my_msg_st some_data;
int msgid;
char buffer[MAX_TEXT];
if( (msgid = msgget((key_t)12345,0666|IPC_CREAT) )== -1 )
{
perror("msgget");
exit(EXIT_FAILURE);
}
printf("msgid:%d\t\n",msgid);
while(running )
{
printf("Enter the message to send:");
fgets( buffer,MAX_TEXT,stdin);
//some_data.my_msg_type =1; //这一句为后来加上的,加上这一句就没有问题了
strcpy(some_data.msg_text,buffer);
if( msgsnd(msgid,(void*)&some_data,MAX_TEXT,IPC_NOWAIT) == -1 )
{
perror("msgsnd");
exit(EXIT_FAILURE);
}
if(strncmp(buffer,"end",3)==0)
{
running=0;
}
}
return 0;
}
/*接收*/
#include
#include
#include
#include
#include
#include
#include
struct my_msg_st
{
long my_msg_type; //消息类型
char msg_text[BUFSIZ];
};
int main(int argc,char ** argv)
{
int running = 1;
struct my_msg_st some_data;
int msgid;
int msg_to_receive =0;
if( (msgid = msgget((key_t)12345,0666|IPC_CREAT) )== -1 )
{
perror("msgget");
exit(EXIT_FAILURE);
}
printf("msgid:%d\t\n",msgid);
while(running )
{
if( msgrcv(msgid,(void*)&some_data,BUFSIZ,msg_to_receive,0)==-1)
{
perror("msgrcv");
exit(EXIT_FAILURE);
}
printf("receiver message:%s",some_data.msg_text);
if(strncmp(some_data.msg_text,"end",3)==0)
{
running=0;
}
}
if(msgctl(msgid,IPC_RMID,0)==-1)
{
fprintf(stderr,"msgctl(IPC_RMID) feiled\n");
exit(EXIT_FAILURE);
}
return 0;
}