IPC object, which is what we call inter-process communication. Next we will summarize what methods and how to use them.
One message queue
1. Create a message queue:
Int msgget (key_t key, int msgflg );
Function: gets the ID of the Message Queue with the specified key value.
Parameters:
@ Key
<1> ipc_private: a new message queue is created each time. [It is used in the process of kinship.]
<2> key obtained by the ftok function [used for inter-kinship communication]
Key_t ftok (const char * pathname, int proj_id );
Function: generate a key value based on the file ID and the low 8bit of proj_id.
Parameters:
@ Pathname: a file name
@ Proj_id: one character
Return Value:
Key is returned successfully.-1 is returned if the request fails.
@ Msgflg: ipc_creat, ipc_excl
Ipc_creat | 0666-> If the message queue of the executed key does not exist, a new message queue is created.
Ipc_creat | ipc_excl-> identifies whether the message queue of the specified key exists. If yes, an error is returned.
Return Value:
Message Queue ID is returned.-1 is returned if a Message Queue fails to be returned.
2. Add a message
Int msgsnd (INT msqid, const void * msgp, size_t msgsz, int msgflg );
Parameters:
@ Msqid: ID of the Message Queue
@ Msgp message storage address
@ Msgsz Message Body Size
@ Msgflg 0: Call ipc_nowait in blocking mode: Call in non-blocking mode
Return Value: 0 is returned for success, and-1 is returned for failure.
Message structure:
Typedef struct
{
// The first field must be of the Message Type
Long type;
// Message Body
Char Buf [1024];
Int PID;
..
} MSG;
// Calculate the message body size
# Define mtxt_size (sizeof (MSG)-sizeof (long ))
3. receive messages
Ssize_t msgrcv (INT msqid, void * msgp, size_t msgsz, long msgtyp, int msgflg );
Parameters:
@ Msqid: ID of the Message Queue
@ Msgp message storage address
@ Msgsz Message Body Size
@ Msgtyp Message Type
@ Msgflg 0: Call ipc_nowait in blocking mode: Call in non-blocking mode
Returned value: the size of the received message body is returned successfully. If the message fails,-1 is returned.
We can use the following example to understand the specific communication mode of the Message Queue:
Communication is performed between two processes, A and B, which are not kinship-related:
Both parties can send and receive messages:
# Include
Another:
#include
Well, the above is about the message queue.