Reputation: 27
I tried to write a message queue that included both the server and the client but when I run the server process, it shows that msgsnd was wrong. The error is Invalid argument! What is wrong?
The max length of message is defined 1024. Apparently this space is big enough.
// msgq.h
#define PATH "/tmp"
#define ID 666
#define MSG_MAX_LEN 1024
struct message{
long mtype;
char mtext[MSG_MAX_LEN];
};
// msgq.c
#include "msgq.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int init_msg_queue() {
key_t KEY = ftok(PATH, ID);
if(KEY==(key_t)-1){
printf("[ LOG ERROR ] ftok faild\n");
return -1;
}
// IPC_CREAT|IPC_EXCL|0666
int msqid = msgget(KEY,IPC_CREAT|0666);
if (msqid < 0){
printf("[ LOG ERROR ] msgget faild\n");
return -1;
}
return msqid;
}
int send_msg(char *msg,int msqid,long type) {
struct message message;
message.mtype=type;
size_t len=strlen(msg);
if(len>MSG_MAX_LEN){
printf("[ LOG ERROR ] Buffer not big enough\n");
return -2;
}
strcpy(message.mtext, msg);
int res=msgsnd(msqid,&message,(size_t)len,0);
if (res==-1){
perror("msg send failed");
return -1;
}
return 0;
}
this is the server.c
include msgq.h and try send message
// server.c
#include "msgq.h"
int main(int args, char *argv[]) {
int qid = init_msg_queue();
if (qid == -1) {
printf("创建/打开队列失败\n");
return 1;
}
while (1) {
send_msg("hello world!", qid, 0);
sleep(2);
}
return 0;
}
Upvotes: 1
Views: 180
Reputation: 14432
Using 'strace ./a.out', it shows:
msgsnd(0, {0, "hello world!"}, 12, 0) = -1 EINVAL (Invalid argument)
Showing two issues:
Fixing: - Change PATH to "/tmp/my-file" (or other file name), which must be a valid, existing, accessible file - In server.c , modify message type to '1' (or other positive integer)
Upvotes: 1