Linux inter-process communication-use Message Queue

Source: Internet
Author: User
The following describes how to use a message queue to communicate between processes. There are many similarities between message queues and named queues. For more information about named MPs queues, see my other article: linux inter-process communication-use Named Pipe 1. What is a message queue Message Queue provides a way to send a data block from one process to another. Each data block is considered to contain a type, and the receiving process can independently receive data structures of different types. We can avoid synchronization and blocking of named pipelines by sending messages. However, like named queues, each data block has a maximum length limit. In Linux, msgmax and msgmnb are used to limit the maximum length of a message and the maximum length of a queue. 2. in Linux, Message Queue Linux provides a series of function interfaces for message queues, allowing us to conveniently use them for inter-process communication. Its usage is similar to the other two System v pic mechanisms, namely, semaphores and shared memory. 1. msgget function this function is used to create and access a message queue. Its prototype is:
int msgget(key_t, key, int msgflg);
Like other IPC Mechanisms, a program must provide a key to name a specific message queue. Msgflg is a permission flag that indicates the access permission of the message queue, which is the same as the access permission of the file. Msgflg can be used with ipc_creat to create a message queue when the message queue named by the key does not exist. If the Message Queue named by the key exists, the ipc_creat flag is ignored, only one identifier is returned. It returns the identifier (non-zero integer) of the Message Queue named after the key. If the key fails, it returns the-1.2 and msgsnd functions. This function is used to add messages to the message queue. Its prototype is:
int msgsend(int msgid, const void *msg_ptr, size_t msg_sz, int msgflg);
Msgid is the message queue identifier returned by the msgget function. Msg_ptr is a pointer to the message to be sent, but the data structure of the message has certain requirements. The message structure pointed to by msg_ptr must start with a long integer member variable, the receiving function uses this member to determine the message type. Therefore, the message structure should be defined as follows:
struct my_message{    long int message_type;    /* The data you wish to transfer*/};
Msg_sz is the length of the message directed by msg_ptr. Note that the message length is not the length of the entire struct. That is to say, msg_sz is not the length of the member variable of the long integer message type. Msgflg is used to control what will happen when the current message queue is full or the queue message reaches the system limit. If the call succeeds, one copy of the message data will be placed in the message queue, and 0 will be returned. If the call fails,-1.3 and msgrcv will be returned. This function is used to retrieve messages from a message queue, its prototype is
int msgrcv(int msgid, void *msg_ptr, size_t msg_st, long int msgtype, int msgflg);
Msgid, msg_ptr, and msg_st functions the same as msgsnd functions. Msgtype implements a simple receiving priority. If msgtype is 0, the first message in the queue is obtained. If the value is greater than zero, the first message with the same message type is obtained. If it is smaller than zero, the first message whose type is equal to or less than the absolute value of msgtype is obtained. Msgflg is used to control what will happen when there is no corresponding type of message in the queue to receive. When the call is successful, the function returns the number of bytes in the receiving cache, the message is copied to the cache allocated by the user directed by msg_ptr, and then the corresponding message in the message queue is deleted. If a message fails, the system returns the-1.4 and msgctl functions. This function is used to control message queues. It is similar to the shmctl function of the shared memory. Its prototype is:
int msgctl(int msgid, int command, struct msgid_ds *buf);
Command is the action to be taken. It can take three values. ipc_stat: sets the data in the msgid_ds structure to the current associated value of the message queue, that is, the value of msgid_ds is overwritten by the current correlation value of the message queue. Ipc_set: if the process has sufficient permissions, set the current association value of the message queue to the value ipc_rmid given in the msgid_ds structure: deleting the Message Queue Buf is a pointer to the msgid_ds structure, it points to the Message Queue mode and access permission structure. The msgid_ds structure includes at least the following members:
struct msgid_ds{    uid_t shm_perm.uid;    uid_t shm_perm.gid;    mode_t shm_perm.mode;};
0 is returned for success, and-1 is returned for failure. 3. Use message queue for inter-process communication. After introducing the definition of message queue and available interfaces, let's take a look at how it enables processes to communicate. Because unrelated processes can communicate with each other, we will write two programs, msgreceive and msgsned, to receive and send messages. Normally, we allow both programs to create messages, but only the receiver deletes the last message after receiving it. The source code of the program that receives information is msgreceive. C:
# Include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <string. h> # include <errno. h> # include <sys/MSG. h> struct msg_st {long int msg_type; char text [bufsiz] ;}; int main () {int running = 1; int msgid =-1; struct msg_st data; long int msgtype = 0; // Note 1 // create a message queue msgid = msgget (key_t) 1234,066 6 | ipc_creat); If (msgid =-1) {fprintf (stderr, "msgget failed with error: % d \ n", errno); exit (exit_failure);} // get the message from the queue, until an End message is received, while (running) {If (msgrcv (msgid, (void *) & Data, bufsiz, msgtype, 0) ==-1) {fprintf (stderr, "msgrcv failed with errno: % d \ n", errno); exit (exit_failure);} printf ("You wrote: % s \ n", Data. text); // If (strncmp (data. text, "end", 3) = 0) Running = 0;} // Delete A Message Queue if (msgctl (msgid, ipc_rmid, 0) =-1) {fprintf (stderr, "msgctl (ipc_rmid) failed \ n"); exit (exit_failure);} exit (exit_success );}
The source code of msgsend. C is:
# Include <unistd. h> # include <stdlib. h> # include <stdio. h> # include <string. h> # include <sys/MSG. h> # include <errno. h ># define max_text 512 struct msg_st {long int msg_type; char text [max_text] ;}; int main () {int running = 1; struct msg_st data; char buffer [bufsiz]; int msgid =-1; // create a message queue msgid = msgget (key_t) 1234,066 6 | ipc_creat); If (msgid =-1) {fprintf (stderr, "msgget failed with error: % d \ n", errno); exit (exit_failure);} // write a message to the message queue, until endwhile (running) {// input data printf ("Enter some text:"); fgets (buffer, bufsiz, stdin); data. msg_type = 1; // Note 2 strcpy (data. text, buffer); // send data to the queue if (msgsnd (msgid, (void *) & Data, max_text, 0) =-1) {fprintf (stderr, "msgsnd failed \ n"); exit (exit_failure);} // enter end of end input if (strncmp (buffer, "end", 3) = 0) Running = 0; sleep (1);} exit (exit_success );}
The running result is as follows: 4. Analyze the example -- message type. Here we mainly describe the message type. Pay attention to msgreceive. the variable msgtype defined in the main function of the C file (note 1), which serves as the value of the parameter for receiving information type of the msgrcv function. Its value is 0, gets the first available message in the queue. Let's take a look at msgsend. the statement data in the while loop in the C file. msg_type = 1 (note 2). It is used to set the type of information sent, that is, the type of information sent is 1. Therefore, the program msgreceive can receive the information sent by the program msgsend. If you note 1, that is, msgreceive. the statement in the main function of the C file is changed from long int msgtype = 0 to long int msgtype = 2; what happens, msgreceive cannot receive the message sent by msgsend. When the msgrcv function is called, if msgtype (fourth parameter) is greater than zero, only the first message with the same message type is obtained, and the modified message type is 2, the Message Type sent by msgsend is 1, so it cannot be received by the msgreceive program. Recompile msgreceive. run the c file again. The result is as follows: msgreceive does not receive the information and output, and msgreceive does not end after msgsend input end, through the jobs command, we can see that it is still running in the background. 5. Comparison between message queues and named MPs queues there are many similarities between message queues and named MPs queues. Like named MPs queues, processes that communicate with MQ can be unrelated processes, at the same time, they both transmit and receive data. In the named pipe, write is used to send data and read is used to receive data. In the message queue, msgsnd is used to send data and msgrcv is used to receive data. They have a maximum length limit for each data. Compared with named queues, message queues have advantages in that: 1. Message queues can also exist independently of the sending and receiving processes, this eliminates the difficulties that may occur when the synchronization named pipe is opened and closed. 2. At the same time, sending messages can also avoid synchronization and blocking of named pipelines, and the process does not need to provide the synchronization method by itself. 3. The receiving program can selectively receive data by message type, rather than receiving data by default, as in the named pipeline.

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.