Programming in Linux-inter-process communication: Message Queue and linux queue

Source: Internet
Author: User

Programming in Linux-inter-process communication: Message Queue and linux queue

Message Queue provides a simple and efficient way to transmit data between two unrelated processes. Its features are as follows:

1) Message Queue supports random query of messages. Messages do not have to be read in the first-in-first-out order, but can be read by message type during programming.

2) A Message Queue allows one or more processes to write or read messages to it.

3) Like an unnamed pipe and named pipe, the data in the message queue is deleted when messages are read from the message queue.

4) each message queue has a message queue identifier, which is unique throughout the system.

5) a message queue is a linked list of messages stored in the memory and maintained by the kernel. The message queue is deleted only when the kernel is restarted or manually deleted. If you do not manually delete a message queue, it will always exist in the system.


Common Message Queue operation functions are as follows:

#include <sys/msg.h>#include <sys/types.h>#include <sys/ipc.h>key_t ftok(const char *pathname, int proj_id);int msgget(key_t key, int msgflg);int msgrcv(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);int msgctl(int msqid, int cmd, struct msqid_ds *buf);

The operations on message queues can be analogous to such a process.: If A has something for B, for some reason, A cannot directly give B to B. At this time, they need to use third-party hosting (such as A bank). A finds the Construction Bank with A specific address, put things in A safe deposit box (for example, safe 1). For B, to successfully retrieve things of A, you must ensure that they are obtained from the same bank at the same address, and only the items in the safe No. 1 are provided by.


The preceding example involves several important information:Address, bank, and safe number.

Only the same address can be guaranteed to be the same bank. Only the two sides of the same bank can use it for hosting. Only the same safe number can be guaranteed to be something hosted by the other party.


In Message Queue operations, the key (key)ValueEquivalent address,Message Queue DescriptorIt is equivalent to a specific bank,Message TypeIt is equivalent to the safe number.

SameKey ValueIt can be the same message queue and the sameMessage Queue DescriptorIn order to ensure that different processes can communicate with each other, the sameMessage TypeIn order to ensure that a process retrieves information from the other party.


1) key Value

The inter-process communication mechanism provided by System V requires a key value to obtain a unique message queue identifier in the System through the key value. The key value can be manually specified or obtained through the ftok () function.


Required header file:

# Include <sys/types. h>
# Include <sys/ipc. h>


Key_t ftok (const char * pathname, int proj_id );

Function:

Obtain the key value

Parameters:

Pathname: path name

Proj_id: Project ID, which is not an integer of 0 (only 8 low digits are valid)

Return Value:

Success: key Value

Failed:-1


2) create a message queue

Required header file:

# Include <sys/msg. h>


Int msgget (key_t key, int msgflg );

Function:

Create a new or open an existing message queue. Different processes call this function to obtain the identifier of the same message queue with the same key value.

Parameters:

Key: key value returned by ftok ()

Msgflg: identifies the function behavior and Message Queue permissions. The values are as follows:

IPC_CREAT: Creates a message queue.

IPC_EXCL: checks whether a Message Queue exists.

Bit or permission bit: After the Message Queue bit or permission bit, you can set the access permission for the message queue. The format is the same as that of mode_t of the open () function (click this link for open ), however, the executable permission is not used.

Return Value:

Success: ID of the Message Queue

Failed:-1


The sample code is as follows:

# Include <stdio. h> # include <unistd. h> # include <stdlib. h> # include <sys/types. h> # include <sys/ipc. h> # include <sys/msg. h> # include <string. h> int main (int argc, char * argv []) {key_t key; int msgqid; key = ftok (". ", 2012); // key value // create Message Queue msgqid = msgget (key, IPC_CREAT | 0666); return 0 ;}


The running result is as follows:



3) read/write operations on message queues

Read/write operations on message queues are based on the message type. The message type is equivalent to the safe number. A places things in the safe 1. The other party wants to take things out of the safe A must also take the things from the safe 1. Similarly, if a process adds a type of message to the message queue, other processes must retrieve the information added by this process.


Before learning the read/write operations of a message queue, we should first learn the Message format of the Message Queue:

Typedef struct _ msg {long mtype; // message type char mtext [100]; // message body ...... ...... // The message body can have multiple members} MSG;

The message type must be a long integer and be the first member of the struct type.The message body contains multiple members (the body member can be of any data type ). As for what the struct type is called and what the Member name is, the struct type is defined by yourself and there is no clear text..


A) add information

Required header file:

# Include <sys/msg. h>


Int msgsnd (int msqid,

Const void * msgp,

Size_t msgsz,

Int msgflg );

Function:

Add a new message to the message queue.

Parameters:

Msqid: The identifier of the message queue.

Msgp: the address of the message structure to be sent.

Msgsz: the number of bytes of the message body.

Msgflg: the control attribute of the function. Its values are as follows:

0: msgsnd () is blocked until the condition is met.

IPC_NOWAIT: if the message is not sent immediately, the process that calls this function will return immediately.

Return Value:

Success: 0

Failed:-1


B) Obtain information

Required header file:

# Include <sys/msg. h>


Ssize_t msgrcv (int msqid,

Void * msgp,

Size_t msgsz,

Long msgtyp,

Int msgflg );

Function:

Receives a message from a Message Queue with the msqid identifier. Once the message is successfully received, the message is deleted in the message queue.

Parameters:

Msqid: The identifier of the message queue, which indicates the message column from which the message is to be obtained.

Msgp: the address that stores the message struct.

Msgsz: the number of bytes of the message body.

Msgtyp:Message Type. It can be of the following types:

Msgtyp = 0: returns the first message in the queue.

Msgtyp> 0: return the message (commonly used) with the Message Type msgtyp in the queue ).

Msgtyp <0: return the message whose type value is smaller than or equal to the absolute value of msgtyp in the queue. If there are several messages, the message with the minimum type value is obtained.


Note: When obtaining a certain type of message, if there are multiple messages of this type in the queue, the first added message is obtained, that is, the first-in-first-out principle.


Msgflg: the control attribute of the function. The value is as follows:

0: msgrcv () is blocked until the message is successfully received.

MSG_NOERROR: if the number of returned message bytes is more than the number of nbytes bytes, the message will be truncated to nbytes bytes without notifying the message sending process.

IPC_NOWAIT: The call process will return immediately. If no message is received,-1 is returned immediately.

Return Value:

Successful: the length of the message to be read.

Failed:-1


3) message queue control

Required header file:

# Include <sys/msg. h>


Int msgctl (int msqid, int cmd, struct msqid_ds * buf );
Function:

Controls message queues, such as modifying Message Queue attributes or deleting message queues.

Parameters:

Msqid: The identifier of the message queue.

Cmd: controls functions. The value is as follows:

IPC_RMID: deletes a Message Queue indicated by msqid, removes it from the system, and destroys the relevant data structure.

IPC_STAT: stores the current values of each element in the data structure related to msqid into the structure directed by buf. Back up the attributes of the message queue to the buf.

IPC_SET: Set the elements in the data structure related to msqid to the corresponding values in the structure pointed to by the buf. It is equivalent to clearing the original attribute values of the message queue and replacing them with buf.

Buf: an address of the msqid_ds data type. It is used to store or change the attributes of a message queue.

Return Value:

Success: 0

Failed:-1


The sample code for writing is as follows:

# Include <stdio. h> # include <unistd. h> # include <stdlib. h> # include <sys/types. h> # include <sys/ipc. h> # include <sys/msg. h> # include <string. h> typedef struct _ msg {long mtype; char mtext [50];} MSG; int main (int argc, char * argv []) {key_t key; int msgqid; MSG msg; key = ftok (". /", 2015); // key value // create Message Queue msgqid = msgget (key, IPC_CREAT | 0666); if (msgqid =-1) {perror ("msgget"); exit (-1);} msg. mtype = 10; // Message Type strcpy (msg. mtext, "hello mike"); // body content/* Add message msg_id: Message Queue identifier & msg: Message structure address sizeof (msg)-sizeof (long ): message Body Size 0: used to use 0 */msgsnd (msgqid, & msg, sizeof (msg)-sizeof (long), 0); return 0 ;}

The read-side sample code is as follows:

# Include <stdio. h> # include <unistd. h> # include <stdlib. h> # include <sys/types. h> # include <sys/ipc. h> # include <sys/msg. h> # include <string. h> typedef struct _ msg {long mtype; char mtext [50];} MSG; int main (int argc, char * argv []) {key_t key; int msgqid; key = ftok (". /", 2015); // key value // create Message Queue msgqid = msgget (key, IPC_CREAT | 0666); if (msgqid =-1) {perror ("msgget"); exit (-1);} MSG msg; memset (& msg, 0, sizeof (msg )); /* msg_id: Message Queue identifier & msg: Message struct address sizeof (msg)-sizeof (long): Message Body Size (long) 10: message Type 0: used to use 0 */msgrcv (msgqid, & msg, sizeof (msg)-sizeof (long), (long) 10, 0); printf ("msg. mtext = % s \ n ", msg. mtext); // Delete A Message Queue // IPC_RMID: Delete the flag msgctl (msgqid, IPC_RMID, NULL); return 0 ;}

The running result is as follows:





For sample code downloading in this tutorial, click here.

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.