* Я использую очереди сообщений для отправки и получения сообщений, но некоторые параметры в структуре 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:
Причина нежелательных значений в этом коде?
struct mesg_q { char msg_txt [100]; long msg_typ; };
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 делает со структурой msqid_ds? msg_typ находится в структуре mesg_q. Ответ на заданный мной вопрос.
Вы отправляете msgq
целиком, вызывая второй аргумент msgsnd()
. Вы должны обновить значение msg_typ
в той же переменной msgq
.
Прежде всего, вы должны знать, зачем использовать message queue
IPC. Я предполагаю, что перед использованием очереди сообщений вы прошли через FIFO
. В FIFO
при каких условиях процессы взаимодействуют друг с другом? что оба процесса должны быть живой во время связи.
Чтобы избежать указанной выше проблемы с FIFO
, вы используете очередь сообщений, так как в MQ вы можете помещать данные за один раз и читать их в любое время, для этого вы должны указать mtype
, то есть с какой mtype
process_1 отправляет данные и с какой mtype
process_2 получает данные.
Со страницы руководства msgsnd
struct msgbuf {
long mtype; /* message type, must be > 0, I'm talking baout this */
char mtext[1]; /* message data */
};
поэтому в обоих процессах (читатель и отправитель) укажите mtype
msgq.msg_typ = 1; /*specify this in both process */
Во-вторых, Время отправки последнего сообщения = 1525240214 - почему отображаются нежелательные значения? => Это не ненужные данные, это время в секундах от времени EPOCH, используйте ctime()
для печати в удобочитаемом формате.
sender.c
#include<stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include<stdint.h>
struct mesg_q {
char msg_txt[100];
long msg_typ;
};
int main(void) {
int msgid;
struct mesg_q msgq;
struct msqid_ds info;
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,sizeof(msgq.msg_txt),stdin);
/* with what msg_type you are sending, you didn't mention ? mention it */
msgq.msg_typ = 1; /* I am sending with msg_type 1 */
if (msgsnd(msgid,&msgq,sizeof(msgq),msgq.msg_typ)==-1) {
printf("Send failed\n");
return -1;
}
else {
printf("Message send\n");
}
msgctl(msgid, MSG_STAT, &info);
printf("Time of last message send = %jd\n",(intmax_t)info.msg_stime);/* use the correct format specifier */
/* what ever time info.msg_stime printing, its not junk, its seconds from EPOCH, use ctime() to print in readable format */
printf("uid = %d\n",info.msg_perm.uid);
}
return 0;
}
Receiver.c
struct mesg_q {
char msg_txt[100];
long msg_typ;
};
int main(void ){
int msgid;
long int rec_buff=0;
struct mesg_q msgq;
struct msqid_ds info;
msgid=msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1) {
printf("Msgget failed\n");
return -1;
}
while(1) {
/* with what msg_typ you are reciving, you have to mention ? u didn't */
msgq.msg_typ = 1;
if (msgrcv(msgid,&msgq,sizeof(msgq),rec_buff, msgq.msg_typ)==-1) {
printf("Mesg recv failed\n");
return -1;
}
else{
printf("Mesg Recvd\n");
}
printf("Recvd mesg=%s\n",msgq.msg_txt);
msgctl(msgid, MSG_STAT, &info);
/* enable compiler warning, and use correct format specifier */
printf("Num:of bytes on queue= %u\n", (int)info.msg_cbytes);
printf("num:of messages on queue=%d\n", (int)info.msg_qnum);
printf("Max bytes on queue=%d\n", (int)info.msg_qbytes);
printf("Time of last message recvd=%jd\n",(intmax_t)info.msg_rtime);
}
return 0;
}
Этот код также дает тот же результат. какая там польза от intnax_t?
Включите флаг предупреждения и установите флажок. Скомпилируйте свой код с помощью -Wall -Wstrict-prototypes -Werror
. Этот код дает такой же результат? какой результат вы ожидаете?
Используйте MSG_STAT
вместо IPC_STAT
Прочтите страницу руководства msgctl()
, в ней говорится, что msg_cbytes
нестандартен. Лучше использовать POSIX ipc
почему я не получаю правильные значения из параметров в struct msqid_ds?
Вы не указали
msg_typ