Linux programming-Message Queuing (14th)

Source: Internet
Author: User
Tags function prototype message queue stdin

14.3 Message Queuing This chapter introduces the third and last system V IPC mechanism; message queue. Message Queuing has many similarities to named pipes, but less complexity in opening and closing pipelines. Using Message Queuing does not address some of the problems that you encounter when using named pipes, such as blocking problems when pipelines are full .
Message Queuing provides a fairly simple and efficient way to pass data between two unrelated processes.
The advantage of Message Queuing over named Pipes is that it exists independently of the sending and receiving processes, eliminating some of the difficulties that can arise when synchronizing named Pipes for opening and closing.
Message Queuing provides a way to send a block of data from one process to another. Also, each block of data is considered to have a type, and the receiving process can independently receive blocks of data that contain different types of values
.

The good news is that you can almost completely avoid the synchronization and blocking problems of named pipes by sending messages. Better yet, there are ways to see the emergency messages in advance.
The bad news is that, like a pipe, each chunk has a maximum length limit, and the total length of all the blocks contained in the system has an upper limit.
The Linux system has two macros that define Msgmax and MSGMNB, each defining the maximum length of a message and the maximum length of a queue, in bytes.
the definition of a message queue function is as follows:
#include <sys/msg.h>int msgctl (int msqid, int cmd, struct msqid_ds *buf), int msgget (key_t key, int msgflg); int MSGRC  V (int msqid, void *msg_ptr, size_t msg_sz, long int msgtype, int msgflg); int msgsnd (int msqid, const void *msg_ptr, size_t MSG_SZ, int msgflg);
Like semaphores and shared memory, header files Sys/types.h and sys/ipc.h are usually msg.h automatically included in the program.
14.3.1 msgget functionfunction ActionThe Msgget function creates and accesses a message queue
Function prototypes
int Msgget (key_t key, int msgflg);
function parameters The first parameter, key, is a key value that names a particular message queue. An unrelated process can access the same message queue through it.
The second parameter, MSGFLG, consists of 9 permission flags. A special bit defined by Ipc_creat must and the permission flag be bitwise OR to create a new message queue.
function return value If successful, returns a positive integer, which is the queue identifier. If it fails, it returns-1
14.3.2 msgsnd functionfunction ActionThe MSGSND function is used to add messages to the message queue.
function prototype int msgsnd (int msqid, const void *msg_ptr, size_t msg_sz, int msgflg);
The structure of a message is constrained by two things.
First of all, it must be less than the system-specified limit
Second, it must start with a long integer member variable that the receive function will use to determine the type of the message.
When using messages, it is a good idea to define the message structure as follows:
struct My_message {
long int message_type;
/* The data wish to transfer */
};
Because Message_type is used in the receipt of a message, it must be included when declaring its own data structure, and it is best to initialize it to a known value.
Function arguments The first parameter msqid is the message queue identifier returned by the Msgget function
The second parameter, MSG_PTR, is a pointer to the ready-to-send message, which must start with a long integer member variable as above
The third parameter, MSG_SZ, is the length of the message pointed to by MSG_PTR, which cannot include the length of a long integer message type member variable
The fourth parameter, MSGFLG, controls what will happen if the current message queue is full or the message queue reaches the limit that the system returns. If the IPC_NOWAIT flag is set in MSGFLG, the function returns immediately without sending a message and the return value is-1. If the ipc_ in MSGFLG When the NOWAIT flag is cleared, the sending process hangs to wait for free space in the queue.
function return value returns 0 if successful (a copy of the message data will be placed in the message queue). If it fails, it returns-1.
14.3.3 MSGRCV functionfunction ActionThe MSGRCV function gets the message from a message queue
function prototype int MSGRCV (int msqid, void *msg_ptr, size_t msg_sz, long int msgtype, int msgflg);
Function arguments The first parameter msqid is the message queue identifier returned by the message function
The second parameter, MSG_PTR, is a pointer to the ready to receive message, and the message must start with a long integer member variable as described in the previous MSGSND function.
The third parameter, MSG_SZ, is the length of the message pointed to by MSG_PTR, which does not include the length of the long integer message type member variable
The fourth parameter, Msgtype, is a long integer that can implement a simple form of receive priority. If the value of Msgtype is 0, the first available message in the queue is obtained. If its value is greater than 0, it gets the first message with the same message type. If its value is less than 0, Gets the first message with a message type equal to or less than the absolute value of Msgtype.
This function looks very complex and is very simple to use. If you want to receive them only in the order in which they are sent, set Msgtype to 0. If you want to get only a particular type of message, set Msgtype to the appropriate type value. If you want to receive a message with a type equal to or less than N, Set the Msgtype to-N.
The fifth parameter, MSGFLG, is used to control what will happen when there is no corresponding type of message in the queue to receive. If the IPC_NOWAIT flag in the MSGFLG is set, the function returns immediately, and the return value is-1. If the IPC_NOWAIT flag in MSGFLG is cleared, The process will hang to wait for a corresponding type of message to arrive.
function return value If successful, returns the number of bytes placed in the receive buffer (the message is copied to the user-allocated buffer that msg_ptr points to, and the corresponding message in the message queue is deleted). If it fails, it returns-1.
14.3.4 msgctl functionfunction ActionThe Msgctl function is very similar to the Shmctl control function for shared memory.
function prototype int msgctl (int msqid, int command, struct msqid_ds *buf);
Function arguments The first parameter msqid is the message queue identifier returned by Msgget
The second parameter command is the action that will be taken, which can take 3 values, as follows:
Command description
Ipc_stat sets the data in the MSQID_DS structure to the current associated 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 given in the MSQID_DS structure
Ipc_rmid Deleting Message Queuing
The third parameter, buf, is a pointer to the structure MSQID_DS.
The MSQID_DS structure contains at least the following members:
struct Msqid_ds {
uid_t Msg_perm.uid;
uid_t Msg_perm.gid;
uid_t Msg_perm.mode;
};
The return value of the function returns 0 if successful. Returns 1 if it fails.
If a process is waiting in the msgsnd or MSGRCV function when Message Queuing is deleted, the two functions will fail.
The experimental Message Queuing writer msg1.c is used to receive messages, and msg2.c is used to send messages.
/************************************************************************* > File name:msg1.c > Description:m SG1.C program for receiving messages > Author:liubingbing > Created time:2015 July 19 Sunday 15:28 22 sec > other:msg1.c ****** /#include <stdio.h> #include <stdlib.h > #include <unistd.h> #include <errno.h> #include <string.h> #include the definition of the <sys/msg.h>/* message structure, The receive function uses the long integer variable my_msg_type to determine the type of the message, Some_text is the data to be passed */struct my_msg_st {long int my_msg_type;char some_text[bufsiz];}; int main () {int running = 1;int msgid;struct my_msg_st some_data;long int msg_to_receive = 0;/* msgget function used to create and access a message queue * First A parameter is a key used to name a particular message queue, and an unrelated process accesses the same message queue * The second parameter is the permission flag * If successful, returns a positive integer, which is the queue identifier. If it fails, return-1 */msgid = Msgget ((key_t) 123, 0666 | Ipc_creat);/* Determines whether the message queue was created successfully */if (MsgId = =-1) {fprintf (stderr, "Msgget failed with Error:%d\n", errno); exit (Exit_failure) ;} while (running) {/* MSGRCV function gets a message from a message queue * the firstThe parameter is the message queue identifier that is returned by the Msgget function * The second parameter is a pointer to the message ready to be received * The third parameter is the length of the messages pointed to * The fourth parameter is a long integer that can implement a simple form of receive priority, set to 0 o'clock, to get the first message in the queue ( Receive them in the order in which they were sent) * The fifth parameter is used to control what happens when no message of the corresponding type in the queue can be received * If successful, returns the number of bytes placed in the receive buffer. If it fails, return -1*/if (MSGRCV (MsgId, (void *) & Some_data, Bufsiz, msg_to_receive, 0) = =-1) {fprintf (stderr, "MSGRCV failed with Error:%d\n", errno); exit (Exit_failure); }/* print Gets the text of the message */printf ("you wrote:%s", some_data.some_text);/* Exit Loop */if If you encounter End (strncmp (Some_data.some_text, "End" , 3) = = 0) {running = 0;}} /* The MSGCTL function is used to control the message * The first parameter is the message queue identifier returned by the Msgget function * The second parameter command is the action to be taken, ipc_rmid means to delete the message queue * The third parameter is a pointer to the MSQID_DS structure * If successful, Returns 0 if it fails, returns 1 */if (Msgctl (MsgId, ipc_rmid, 0) = =-1) {fprintf (stderr, "Msgctl (ipc_rmid) failed\n"); Exit (exit_failure );} Exit (exit_success);}
Msg2.c
/************************************************************************* > File name:msg2.c > Description:m SG2.C for sending messages > author:liubingbing > Created time:2015 July 19 Sunday 16:07 47 seconds > Other:msg2.c ******** /#include <stdio.h> #include <stdlib.h > #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/msg.h> #define MAX _text 512struct my_msg_st {long int my_msg_type;char some_text[max_text];}; int main () {int running = 1;struct My_msg_st some_data;int msgid;char buffer[bufsiz];/* msgget function Create or access Message Queuing * First parameter key name a specific Message Queuing, the unrelated process passes it to get the same message queue * The second parameter is the permission flag * If successful, returns a positive integer, which is the queue identifier. If it fails, it returns-1 */msgid = Msgget ((key_t) 123, 0666 | Ipc_creat); if (MsgId = =-1) {fprintf (stderr, "Msgget failed with Error:%d\n", errno); exit (exit_failure);} while (running) {printf ("Enter some text:");/* Reads Bufsiz bytes of data from the standard input stdin to buffer pointing memory */fgets (buffer, bufsiz, stdin);/* WillFlag My_msg_type is set to 1, gets the first message with the same type (1) */some_data.my_msg_type = 1;/* copies data from buffer to Some_data.some_text */strcpy (some_ Data.some_text, buffer);/* MSGSND function adds message to message queue * The first parameter is the message queue identifier returned by the Msgget function * The second parameter is a pointer to the ready to send message * The third parameter is the length of the message * The fourth parameter is what MSGFLG controls when the current message queue is full or the queue message reaches the limit that the system returns. * If successful, returns 0. If it fails, 1 */if (Msgsnd (MsgId, (void *) &some_data, Max_ TEXT, 0) = =-1) {fprintf (stderr, "msgsnd failed\n"); exit (exit_failure);} if (strncmp (buffer, "End", 3) = = 0) {running = 0;}} Exit (exit_success);}
Allows two programs to create a message queue, but only the recipient can delete it after the last message has been received.
Sender program msg2.c and msg1.c very similar, in the main function of the variable definition section, delete the definition of msg_to_receive and replace it with Buffer[bufsiz]. Remove the statement that deletes the message queue, Make the following changes in the running loop. Sends the user-entered text to the message queue by calling Msgsnd.
Unlike the pipeline example, Message Queuing does not require the process to provide the synchronization method itself, which is a distinct advantage of the message relative to the pipeline.
Assuming there is space in the message queue, the sender can create a queue, put some data into the queue, and then exit before the recipient starts. Run Sender MSG2 first. The following is shown:

Program parsing The Sender program creates a message queue through Msgget, and then adds the message to the queue with MSGSND, the recipient obtains the message queue identifier with Msgget, and then begins to receive the message. Until a special text end is received. It then uses MSGCTL to delete the message queue to complete the cleanup work.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux programming-Message Queuing (14th)

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.