This is used for reading a message from a specified message queue whose identifier is supplied. Here is its syntax:
int msgrcv(int msqid, void *msgstruc, int msgsize, long typemsg, int flag);
Here, we have to address the following:
- msqid: Represents the message queue identifier of the queue from which the message needs to be read.
- msgstruc: This is the user-defined structure into which the read message is placed. The user-defined structure must contain two members. One is usually named mtype, which must be of type long int that specifies the type of the message, and the second is usually called mesg, which should be of char type to store the message.
- msgsize: Represents the size of text to be read from the message queue in terms of bytes. If the message that is read is larger than msgsize, then it will be truncated to msgsize bytes.
- typemsg: Specifies which message on the queue needs to be received:
- If typemsg is 0, the first message on the queue is received
- If typemsg is greater than 0, the first message whose mtype field is equal to typemsg is received
- If typemsg is less than 0, a message whose mtype field is less than or equal to typemsg is received
- flag: Determines the action to be taken if the desired message is not found in the queue. It keeps its value of 0 if you don't want to specify the flag. The flag can have any of the following values:
- IPC_NOWAIT: This makes the msgrcv function fail if there is no desired message in the queue, that is, it will not make the caller wait for the appropriate message on the queue. If flag is not set to IPC_NOWAIT, it will make the caller wait for an appropriate message on the queue instead of failing the function.
- MSG_NOERROR: This allows you to receive text that is larger than the size that's specified in the msgsize argument. It simply truncates the text and receives it. If this flag is not set, on receiving the larger text, the function will not receive it and will fail the function.
If the function is executed successfully, the function returns the number of bytes that were actually placed into the text field of the structure that is pointed to by msgstruc. On failure, the function returns a value of -1.