您的位置:首页 > 运维架构 > Linux

linux进程间通信消息队列:msgsnd: Invalid argument

2013-09-12 22:53 477 查看
今天写了个消息队列的小测试程序结果send端程序总是出现:msgsnd: Invalid argument,搞了半个小时也没搞明白,后来查资料发现我将(st_msg_buf.msg_type = 0; //设置消息类型)设置为0了,原来0表示是任意类型的消息,只有recv端才可以设置为0表示:可以接受任意类型消息。

代码:

发送端源代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>

#define MAX_TEXT      512
#define BUF_SIZE    512

struct my_msg_st{            //临时消息结构

int  msg_type;
char msg_text[MAX_TEXT];        //自定义存储空间大小
};

int main()
{
key_t key;
int  running  = 1;
struct my_msg_st st_msg_buf;
int msgid;
char buffer[BUF_SIZE];
memset(&st_msg_buf, 0, sizeof(st_msg_buf));
memset(buffer, 0, sizeof(buffer));

//创建键值
if((key = ftok("./", 100)) == -1){
perror("ftok");
exit(1);
}
printf("key : %#x\n", key);

//创建信息队列
if((msgid = msgget(key, 0666 | IPC_CREAT)) == -1){
perror("msgget");
exit(1);
}
printf("Enter the messge to send:");

//发送消息
while(running)
{
fgets(buffer, BUF_SIZE, stdin);//读取输入的消息
if(buffer[0] == '\0' || buffer[0] == '\n')
continue;
buffer[strlen(buffer) - 1] = '\0';//去回车符
st_msg_buf.msg_type = 1;       //设置消息类型
strcpy(st_msg_buf.msg_text, buffer);//复制消息

printf("message have send to\n");
if(msgsnd(msgid, (void *)&st_msg_buf, MAX_TEXT, 0) < 0){
perror("msgsnd");
exit(1);
}

if(strncmp(buffer, "end", 3) == 0)//判断是否为退出结束消息
running = 0;

}

return 0;
}


接收端源代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>

#define MAX_TEXT      512
#define BUF_SIZE    512

struct my_msg_st{            //临时消息结构

int  msg_type;
char msg_text[MAX_TEXT];        //自定义存储空间大小
};

int main()
{
key_t key;
int running  = 1, size = 0;
struct my_msg_st st_msg_buf;
int msgid;
int msg_to_receiver = 0;
memset(&st_msg_buf, 0, sizeof(st_msg_buf));

//创建键值
if((key = ftok("./", 100)) == -1){
perror("ftok");
exit(1);
}
printf("key : %#x\n", key);

//创建信息队列
if((msgid = msgget(key, 0666 | IPC_CREAT)) == -1){
perror("msgget");
exit(1);
}

//接受消息
while(running)
{
if((size = msgrcv(msgid, (void *)&st_msg_buf,
MAX_TEXT, msg_to_receiver,0)) <  0){
perror("msgsnd");
exit(1);
}

printf("receiver mssage: %d, %s\n", size, st_msg_buf.msg_text);

if(strncmp(st_msg_buf.msg_text, "end", 3) == 0)
running = 0;
}

if(msgctl(msgid, IPC_RMID, 0) < 0){
perror("msgctl");
exit(1);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: