gpt4 book ai didi

c - 关于 POSIX 消息队列和无效参数

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:18 26 4
gpt4 key购买 nike

我试着写了一个包含服务器端和客户端的消息队列但是当我运行服务器进程时,它显示 msgsnd 是错误的。错误是参数无效!怎么了?

消息的最大长度定义为1024,显然这个空间足够大了。

// 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;
}

这是server.c
包含 msgq.h 并尝试发送消息

// 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;
}

最佳答案

使用'strace ./a.out',它显示:

msgsnd(0, {0, "hello world!"}, 12, 0) = -1 EINVAL (Invalid argument)

显示两个问题:

  • “sockfd”为零。 sockfd 是使用“/tmp”目录中的“ftok”创建的。根据 ftok 手册页:'ftok() 函数使用由给定路径名命名的文件的标识(必须引用现有的可访问文件'(而不是目录)。
  • “messagetype”属性为 0,而手册页指出“mtype 字段必须具有严格的正整数值。”

修复: - 将 PATH 更改为“/tmp/my-file”(或其他文件名),该文件必须是有效的、现有的、可访问的文件 - 在 server.c 中,将消息类型修改为 '1'(或其他正整数)

关于c - 关于 POSIX 消息队列和无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58230631/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com