Communication Message Queue between Linux Processes

Source: Internet
Author: User

A message queue is a list of messages. You can add messages to a message queue.
And read messages. Message Queue has certain FIFO features, but it can be implemented
The random query of messages has a greater advantage than FIFO. At the same time, these messages
It exists in the kernel and is identified by the queue ID.
The implementation of Message Queue includes creating or opening a message queue, adding a message, and reading
Messages and control message queues.
1. Create or open a message queue, msgget (), the number of created message queues will be affected
Limit on the number of system message queues
Msgget (create or open a Message Queue)
Header file # include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/msg. h>
The function defines int msgget (key_t key, int msgflg );
Function Description key: the key value associated with the message queue, the return value of ipc_private or ftok
Msgflag: Message Queue access permission
Success: the message queue ID is returned, and-1 is returned for an error.
Linux_c # IPCS-Q // view the Message Queue

------ Message queues --------
Key msqid owner perms used-bytes messages
2. Add a message queue. msgsnd () adds the message to the inner end of the opened message queue.
Header file # include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/SHM. h>
Function Definition int msgsnd (INT msqid, const void * msgp, size_t msgsz, int msgflg)
Msgqit: the ID of the message queue.
Msgp: pointer to the message structure. The message structure msgbuf is generally:
Struct msgbuf
{
Long mtype; // message type. The structure must start from this domain.
Char mtext [1]; // Message Body
};
Msgsz: number of bytes of the message body (excluding the Message Type pointer variable)
Msgflg: ipc_nowait: If a message cannot be sent immediately (for example, the current message queue is full)
The function returns immediately.
0: msgsnd call blocking until sending is successful
Returned value: 0 success, error-1
3. msgrcv () reads the message queue, which removes the message from the message queue. Different from FIFO
Removes a specified message.
Msgrcv (receive messages)
Header file # include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/msg. h>
Function Definition ssize_t msgrcv (INT msqid, void * msgp, size_t msgsz, long msgtyp, int msgflg );
Function Description parameter msgid: ID of the message queue, msgp: buffer for receiving messages, msgsz: number of bytes for receiving messages. Note that the type is consistent.
Msgtype:

0: receives the first message in the message queue.
Greater than 0: receives the first message of msgtyp type in the message queue.
Smaller than 0: The type value in the received message queue is not smaller than the absolute value of msgtyp and the type value is the smallest.
Msgflag:
0: If there is no message, the function will be blocked all the time.
Ipc_nowait: If no message exists, the process immediately returns enomsg.
4. msgctl () controls message queues
Msgctl (delete, retrieve, and set message queues)
Header file: # include <sys/types. h>
# Include <sys/IPC. h>
# Include <sys/msg. h>
Function Syntax: int msgctl (INT msqid, int cmd, struct msqid_ds * BUF );
Function Description: msgid: Message Queue ID
CMD: ipc_stat: Read the attributes of the message queue and save them in the buffer zone to which the Buf points.
Ipc_set: Set the attributes of the message queue. This value is taken from the Buf parameter.
Ipc_rmid: deletes a message queue from the system.
Buf: Message Queue Buffer
Returned value: Success 0; error-1
The msqid_ds data structure is defined in <sys/msg. h> as follows:

Struct msqid_ds {
Struct ipc_perm msg_perm;/* ownership and permissions
Time_t msg_stime;/* time of last msgsnd ()*/
Time_t msg_rtime;/* time of last msgrcv ()*/
Time_t msg_ctime;/* time of last change */
Unsigned long _ msg_cbytes;/* current number of bytes in
Queue (non-standard )*/
Msgqnum_t msg_qnum;/* current number of messages
In queue */
Msglen_t msg_qbytes;/* Maximum number of bytes
Allowed in queue */
Pid_t msg_lspid;/* PID of last msgsnd ()*/
Pid_t msg_lrpid;/* PID of last msgrcv ()*/
};
-------------------------------------------------------
For example, two message queues are used for communication between two processes (sending and receiving ends), including message queues.
Creation, message sending and reading, revocation and deletion of Message Queues
There is no need to synchronize processes between the sender process and the receiver process.

Function ftok (), which can generate standard keys based on different paths and keywords.

-------------------------------------------------------- Msg_com.h ## ifndef _ msg_com_h __# DEFINE _ msg_com_h __# include <sys/types. h> # include <sys/IPC. h> # include <sys/MSG. h> # include <stdio. h> # include <stdlib. h> # include <unistd. h> # include <string. h> # define buffer_size 512 struct message {long msg_type; // message type char msg_text [buffer_size]; // message body}; # endif delayed msgsnd. C # include "msg_com.h"/*** Message Queue sender */INT main (INT argc, char ** argv) {int qid; key_t key; struct message MSG; // generate a standard keyif (Key = ftok (". ", 'C') =-1) {perror (" ftok "); exit (1);} // create a message queue qid = msgget (key, ipc_creat | 0666); If (qid =-1) {perror ("msgget"); exit (1) ;}printf ("Open queue % d \ n ", qid); While (1) {printf ("Enter some message to the queue (quit to exit): \ n"); If (fgets (MSG. msg_text, buffer_size, stdin) = NULL) {puts ("fgets"); exit (1);} MSG. msg_type = getpid (); // Add a message to the Message Queue if (msgsnd (qid, & MSG, strlen (MSG. msg_text), 0) <0) {perror ("msgsnd"); exit (1);} If (strncmp (MSG. msg_text, "quit", 4) = 0) {break;} exit (0);} --------------------------------------------------- msgrcv. C # include "msg_com.h"/*** Message Queue receiver */INT main (INT argc, char ** argv) {int qid; key_t key; struct message MSG; if (Key = ftok (". ", 'C') =-1) {perror (" ftok "); exit (1);} // create a message queue if (qid = msgget (key, ipc_creat | 0666) =-1) {perror ("msgget"); exit (1);} printf ("Open queue % d \ n", qid ); do {// read the message queue memset (MSG. msg_text, 0, buffer_size); If (msgrcv (qid, (void *) & MSG, buffer_size, 0, 0) <0) {perror ("msgrcv "); exit (1);} printf ("the message from process % ld: % s \ n", MSG. msg_type, MSG. msg_text);} while (strncmp (MSG. msg_text, "quit", 4); // remove the Message Queue from the system kernel if (msgctl (qid, ipc_rmid, null) <0) {perror ("msgctl"); exit (1);} exit (0);} -------------------------------------------------------------- test result msgque #. /msgsndopen queue 163840 enter some message to the queue (quit to exit): Good dayenter some message to the queue (quit to exit ): day is good dayenter some message to the queue (quit to exit): Time is moneyenter some message to the queue (quit to exit): quitmsgque #. /msgrcvopen queue 163840the message from process 6150: Good daythe message from process 6150: day is good daythe message from process 6150: Time is moneythe message from process 6150: Quit
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.