Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use message queuing in Linux interprocess communication

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

What this article shares to you is about how to use message queue in Linux inter-process communication. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

What is message queuing

Message queuing provides a way to send a block of data from one process to another. Each data block is considered to contain a type, and the receiving process can independently receive data structures containing different types. We can avoid the synchronization and blocking problems of named pipes by sending messages. But message queuing, like named pipes, has a limit on the length of each data block.

Linux uses macros MSGMAX and MSGMNB to limit the length of a message and the length of a queue.

Using message queuing in Linux

Linux provides a series of functional interfaces for message queues so that we can easily use it to achieve inter-process communication. Its usage is similar to the other two System V PIC mechanisms, 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, the program must provide a key to name a particular message queue. Msgflg is a permission flag that indicates access to a message queue, which is the same as access to a file. Msgflg can operate with IPC_CREAT to create a message queue when the message queue named by key does not exist, and if the message queue named by key exists, the IPC_CREAT flag is ignored and only an identifier is returned.

It returns the identifier (non-zero integer) of a message queue named key, or-1. 0 on failure.

2. Msgsnd function

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 ready to be sent, but the data structure of the message has certain requirements. The message structure pointed to by the pointer msg_ptr must start with a long integer member variable, and the receiving function will use this member to determine the type of message. So the message structure should be defined like this:

Struct my_message {long int message_type; / * The data you wish to transfer*/}

Msg_sz is the length of the message pointed to by msg_ptr. Note that it is the length of the message, not the length of the entire structure, that is, msg_sz does not include the length of long integer message type member variables.

Msgflg is used to control what happens when the current message queue is full or when a queue message reaches a system-wide limit.

If the call is successful, a copy of the message data is placed in the message queue and returns 0 or-1 on failure.

3. Msgrcv function

This function is used to get a message from a message queue, and its prototype is

Int msgrcv (int msgid, void * msg_ptr, size_t msg_st, long int msgtype, int msgflg)

The functions of msgid, msg_ptr and msg_st are the same as those of msgsnd function.

Msgtype can implement a simple receive priority. If msgtype is 0, get * messages in the queue. If its value is greater than zero, it will get * * information with the same message type. If it is less than zero, get * messages of type equal to or less than the absolute value of msgtype.

Msgflg is used to control what happens when there are no messages of the corresponding type in the queue to receive.

When the call is successful, the function returns the number of bytes placed in the receive cache, the message is copied to the cache assigned by the user pointed to by the msg_ptr, and then the corresponding message in the message queue is deleted. Returns-1 on failure.

4. Msgctl function

This function is used to control the message queue, which is similar to the shmctl function in 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 association value of the message queue, that is, overwrites the value of msgid_ds with the current association value of the message queue.

IPC_SET: if the process has sufficient permissions, set the current correlation value of the message queue to the value given in the msgid_ds structure

IPC_RMID: deleting message queues

Buf is a pointer to the msgid_ds structure, which points to the message queuing pattern and the structure of access permissions. The msgid_ds structure consists of at least the following members:

Struct msgid_ds {uid_t shm_perm.uid; uid_t shm_perm.gid; mode_t shm_perm.mode;}

Returns 0 on success and-1 on failure.

Third, use message queuing for interprocess communication

Non-stop, after introducing the definition of message queue and the interfaces available, let's take a look at how it allows processes to communicate. Since it is possible for unrelated processes to communicate with each other, we will write two programs, msgreceive and msgsned, to represent receiving and sending messages. Under normal circumstances, we allow both programs to create a message, but it deletes a message only after the recipient has received it.

The source file of the program that receives the information is msgreceive.c. The source code is:

# include # include 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 / / establish message queue msgid = msgget ((key_t) 1234, 0666 | IPC_CREAT); if (msgid = =-1) {fprintf (stderr, "msgget failed with error:% d\ n", errno); exit (EXIT_FAILURE) } / / get message from queue until end message is encountered 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); / / encounter end end if (strncmp (data.text, "end", 3) = = 0) running = 0 } / / delete 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 for the source file msgsend.c of the program that sends the information is:

# include # 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 / / establish message queue msgid = msgget ((key_t) 1234, 0666 | IPC_CREAT); if (msgid = =-1) {fprintf (stderr, "msgget failed with error:% d\ n", errno); exit (EXIT_FAILURE) } / / write messages to the message queue until end while (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 end input if (strncmp (buffer, "end", 3) = = 0) running = 0; sleep (1);} exit (EXIT_SUCCESS);}

The running results are as follows:

IV. Example analysis-message types

This mainly explains what the message type is all about. Note the variable msgtype defined in the main function of the msgreceive.c file (note 1). As the value of the received information type parameter of the msgrcv function, the value is 0, which means to get * messages available in the queue. Let's take a look at the statement data.msg_type = 1 in the while loop in the msgsend.c file, which is used to set the type of information sent, that is, the type of information it sends is 1. So the program msgreceive can receive the information sent by the program msgsend.

If you take note 1, that is, the statement in the main function of the msgreceive.c file is changed from long int msgtype = 0; to long int msgtype = 2; what happens, msgreceive will not be able to receive the information sent by the program msgsend. Because when calling the msgrcv function, if msgtype (the fourth parameter) is greater than zero, only * * messages with the same message type will be obtained. The modified message type is 2, while the message type sent by msgsend is 1, so it cannot be received by the msgreceive program. Recompile the msgreceive.c file and execute it again. The result is as follows:

We can see that the msgreceive does not receive the information and output, and when the msgsend input end ends, the msgreceive is not finished, through the jobs command we can see that it is still running in the background.

5. Comparison between message queues and named pipes

Message queuing has a lot in common with named pipes. Like named pipes, the processes that message queues communicate can be unrelated processes, and they both transmit data by sending and receiving. In the named pipeline, send data with write, receive data with read, then in message queue, send data with msgsnd and receive data with msgrcv. And they have a limit on the length of each data.

Compared with named pipes, message queuing has the advantage of: 1. Message queues can also exist independently of sending and receiving processes, thus eliminating the difficulties that may arise when synchronous named pipes are opened and closed. 2. At the same time, the synchronization and blocking of named pipes can be avoided by sending messages, and the synchronization method does not need to be provided by the process itself. 3. The receiver can selectively receive data through the message type, rather than by default, as in named pipes.

The above is how to use message queuing in Linux inter-process communication. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report