【发布时间】:2018-10-12 04:15:03
【问题描述】:
*我正在使用消息队列来发送和接收消息,但是结构 msqid_ds 中的某些参数没有给出正确的值,为什么会发生这种情况? *最后一条消息发送的时间=1525240214-为什么显示垃圾值?
struct mesg_q
{
char msg_txt[100];
long msg_typ;
};
int main()
{
int msgid;
key_t key;
char buffer[100];
struct mesg_q msgq;
struc answerst msqid_ds info;
// key = ftok("/home/yash72/krishna/thread_test/msgq.text", 65);
msgid=msgget((key_t)1234, 0666 | IPC_CREAT);
if(msgid== -1)
{
printf("msgget failed\n");
return -1;
}
while(1)
{
printf("Text Message\n");
fgets(msgq.msg_txt,100,stdin);
if(msgsnd(msgid,&msgq,100,0)==-1)
{
printf("Send failed\n");
return -1;
}
else
{
printf("Message send\n");
}
msgctl(msgid, IPC_STAT, &info);
printf("Time of last message send=%d\n",info.msg_stime);
printf("uid=%d\n",info.msg_perm.uid);
}
}
OUTPUT:
Text Message
qwerty
Message send
Time of last message send=1525240214 // Why this is showing junk?
uid=0
Text Message
Receiver code:
-
此代码中的垃圾值的原因是什么?
结构mesg_q { 字符 msg_txt[100]; 长消息类型; };
int main() { int msgid; char buffer[100]; long int rec_buff=0; key_t key; struct mesg_q msgq; struct msqid_ds info; // key = ftok("/home/yash72/krishna/thread_test/msgq.text", 65); msgid=msgget((key_t)1234, 0666 | IPC_CREAT); if(msgid == -1) { printf("Msgget failed\n"); return -1; } while(1) { if(msgrcv(msgid,&msgq,100,rec_buff,0)==-1) { printf("Mesg recv failed\n"); return -1; } else { printf("Mesg Recvd\n"); } printf("Recvd mesg=%s\n",msgq.msg_txt); msgctl(msgid, IPC_STAT, &info); printf("Num:of bytes on queue= %d\n", info.msg_cbytes); printf("num:of messages on queue=%d\n", info.msg_qnum); printf("Max bytes on queue=%d\n", info.msg_qbytes); printf("Time of last message recvd=%d\n",info.msg_rtime); } }输出;
队列上的字节数= 0 队列上的消息数=0 队列上的最大字节数=16384 最后收到消息的时间=1525240214
从 struct msqid_ds 得到这个不正确值的原因是什么?
【问题讨论】:
-
你没有指定
msg_typ -
msg_typ 对结构 msqid_ds 做了什么? msg_typ 在结构 mesg_q 中。回答我提出的问题。
-
您通过调用
msgsnd()第二个参数发送整个msgq。您应该更新同一msgq变量中的msg_typ值。
标签: c linux message-queue