Home > Back-end >  Message queuing problem, bosses to reassure
Message queuing problem, bosses to reassure

Time:09-23

The code below
 # include "is basic. H" 

Int main (int arg c, char * argv [])
{
Key_t key;
Pid_t fpid;
Int msgqid, ret;
MSG msg01;
Char buf [150].
Char * saveptr=NULL;

Key=ftok ("./test. TXT ", 1);
If (1==key)
{
Perror (" ftok fail ");
exit(-1);
}
Ret=MSGCTL (4, IPC_RMID, NULL);//delete existing message queue before
If (1==ret)
{
Perror (" MSGCTL fail ");
exit(-1);
}
Ret=0;
Msgqid=msgget (key, IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
If (1==msgqid)
{
Perror (" msgget fail ");
exit(-1);
}

Fpid=fork ();
If (fpid & lt; 0)
{
Perror (" fork fail ");
exit(-1);
}
Else if (0==fpid)//the child
{
While (1)
{
Ret=0;
Sleep (5);
/* printf (" input message types: \ n ");
The scanf (" % ld, "msg01. Type); */
Printf (" input message content: (format: type: the sender: content) \ n ");
Memset (buf, '\ 0', sizeof (buf));
The scanf (" % [^ \ n] ", buf);
Msg01. Type=atol (strtok_r (buf, ":", & amp; Saveptr));
Strcpy (msg01. Name, strtok_r (saveptr, ":", & amp; Saveptr));
Strcpy (msg01. Text, saveptr);
Printf (" sends the message type: % ld \ n message sender: % s \ n content of the message: % s \ n ", msg01. Type, msg01. Name, msg01. The text).
Ret=MSGSND (msgqid, & amp; Msg01, sizeof (msg01. Text), 0);
If (1==ret)
{
Perror (" MSGSND fail ");
exit(-1);
}
If (0==STRCMP (msg01. Text, "the end"))
{
break;
}
}
return 0;
}
The else//parent
{
While (1)
{
Ret=0;
Ret=MSGRCV (msgqid, & amp; Msg01, sizeof (msg01. Text) - 10, 0);
If (1==ret)
{
Perror (" MSGRCV fail ");
exit(-1);
}
Printf (" received message types: % ld \ n message sender: % s \ n content of the message: % s \ n ", msg01. Type, msg01. Name, msg01. The text).
Printf (" at the end of the message to accept \ n ");
If (0==STRCMP (msg01. Text, "the end"))
{
break;
}
}
Wait (NULL).
Ret=0;
Ret=MSGCTL (msgqid IPC_RMID, NULL);//delete the message queue
If (1==ret)
{
Perror (" msgctl2 fail ");
exit(-1);
}
return 0;
}
return 0;
}


Message structure
 typedef struct MSG 
{
Long type.
Char text [100].
Char name [20].
} MSG.


The child process sending a message to the parent receive messages, you can run for the first time, but the second after the second process input information is stuck, no reaction, another problem is the message content: the name is missing, and bosses,

The results indicated:

CodePudding user response:

The parent part break the front print in a word, a look likely to break out

CodePudding user response:

Problem has been solved, stuck reason is
 the scanf (" % [^ \ n] ", buf); 

Somehow can only enter once, instead of after the fgets input problem solving,
Packet loss is MSGSND input parameter is wrong, after correction,
  • Related