linux消息队列收到乱码,从Linux上的消息队列中读取时出错"Bad address"

当我需要编写简单的时间服务器和使用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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值