jcu*_*bic 3 c unix linux message-queue
当我需要编写简单的时间服务器和使用Linux消息队列的客户端时,我有分配.服务器打开一个消息队列,客户端发送一个带有PID的消息(类型为1的消息),服务器读取该消息并发送一个PID类型的消息(取自读取的消息).我把所有代码都放在下面,因为我不知道我在哪里弄错了.我不是Linux编程专家.甚至不知道我写的服务器是否正确.
服务器和客户端包含的文件(我需要以这种方式编写).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <string.h>
#include <signal.h>
#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;
Run Code Online (Sandbox Code Playgroud)
服务器
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);
}
Run Code Online (Sandbox Code Playgroud)
客户
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;
}
Run Code Online (Sandbox Code Playgroud)
两个程序编译没有错误,但客户端返回"错误从队列读取"msgrcv返回-1.
添加之后perror,似乎您已经收到错误说明"Bad Address"(EFAULT),这意味着" msgp(缓冲区)指向的地址不可访问".从代码中可以看出,没有分配内存,TimeMessage *t因此您可以分配内存或只是将其更改为TimeMessage tand &t而不是tto msgrcv.另外大小应sizeof t(从假设的变化*t来t,或sizeof(TimeMessage)对*t),而不是sizeof(struct tm)(显然,你会改变printf相应语句)
希望这有助于!