当我需要编写简单的时间服务器和使用Linux消息队列的客户端时,我有分配.服务器打开一个消息队列,客户端发送一个带有PID的消息(类型为1的消息),服务器读取该消息并发送一个PID类型的消息(取自读取的消息).我把所有代码都放在下面,因为我不知道我在哪里弄错了.我不是Linux编程专家.甚至不知道我写的服务器是否正确.
服务器和客户端包含的文件(我需要以这种方式编写).
#include
#include
#include
#include
#include
#include
#include
#include
#define QUEUE 100
#define PERM_ALL 0777
typedef struct my_msgbuf {
long mtype;
int pid;
} ClientMessage;
typedef struct my_msgbuf2 {
long mtype;
struct tm time;
} TimeMessage;
服务器
int m_queue;
void cleanup(int signum) {
if (msgctl(m_queue, IPC_RMID, NULL) == -1) {
printf("Something happen on clean up\n");
exit(1);
}
exit(signum);
}
int main() {
ClientMessage pid_message;
TimeMessage t;
time_t clock;
struct tm *cur_time;
if ((m_queue = msgget(QUEUE, PERM_ALL | IPC_CREAT)) == -1) {
printf("Can't create and open message queue\n");
exit(1);
}
printf("created message queue = %d\n", m_queue);
fflush(stdout);
//t = malloc(sizeof(TimeMessage));
signal(SIGINT, cleanup);
while (1) {
if (msgrcv(m_queue, &pid_message, sizeof(pid_message.pid), 1, 0) == -1) {
break;
} else {
t.mtype = pid_message.pid;
clock = time(NULL);
cur_time = localtime(&clock);
memcpy(&t.time, cur_time, sizeof(struct tm));
msgsnd(m_queue, &t, sizeof(struct tm), 0);
}
}
cleanup(0);
}
客户
int main() {
int m_queue;
TimeMessage *t;
ClientMessage client;
if ((m_queue = msgget(QUEUE, PERM_ALL)) == -1) {
perror("Error in opening queue");
exit(1);
}
client.mtype = 1;
client.pid = getpid();
while (1) {
if (msgsnd(m_queue, &client, sizeof(client.pid), 0) == -1) {
perror("Error sending to queue");
exit(1);
} else {
if (msgrcv(m_queue, t, sizeof(struct tm), client.pid, 0) == -1) {
perror("Error reading from queue");
exit(1);
}
printf("time: %d:%d:%d\n", t->time.tm_hour, t->time.tm_min, t->time.tm_sec);
}
}
return 0;
}
两个程序编译没有错误,但客户端返回“错误从队列读取”msgrcv返回-1.
解决方法:
添加完错误之后,似乎您收到错误,指出“错误地址”(EFAULT),这意味着“msgp(缓冲区)指向的地址不可访问”.从代码中可以看出,没有为TimeMessage * t分配内存,因此您既可以分配内存,也可以将其更改为TimeMessage t,并将&t而不是t传递给msgrcv.大小也应该是sizeof t(假设从* t到t的变化,或者对于* t的sizeof(TimeMessage)而不是sizeof(struct tm)(并且显然你会相应地更改printf语句)
希望这可以帮助!
标签:c-3,linux,unix,message-queue
来源: https://codeday.me/bug/20190826/1729006.html