Inter-process communication 05 Message Queue

Source: Internet
Author: User
I. OverviewThe message queue is A memory area with a certain format, that is, Linked ListIn the kernel, messages can be viewed as a record, which has a specific format and priority. Message Queue The read and write operations are asynchronous.The sender does not have to wait for the receiver to receive the data, and the receiver does not have to wait. New messages are always placed at the end of the team. When receiving new messages, you do not have to follow the first-in-first-out principle. Get data based on priority. The message queue is only available in The kernel is deleted only when it is restarted or displayed..
2. operation functions 1. Create a Message Queue
# Include <sys/types. h> # include <sys/IPC. h> # include <sys/MSG. h> int msgget (key_t key, // key value, identifies the unique int msgflg of the Message Queue); // set the attributes of the message queue. Generally 0666 | ipc_creat // return value:> 0 (success, Message Queue identifier)-1 (creation failed, failed information see errno)



2. Shell check method after creationIPCS-q | grep-I key, for example, IPCS-q | grep-I 4d2: view the Message Queue with the key value of 1234 (the 16 process is 4d2)



3. Write Data to the Message Queue
# Include <sys/IPC. h> # include <sys/MSG. h> # include <sys/types. h> int msgsnd (INT msqid, // Message Queue identifier const void * msgp, // struct pointer containing data size_t msgsz, // length of data in struct int msgflg ); // set some features for sending data // return value: 0 (Data Writing succeeded)-1 (Data Writing failed. For error information, see errno)

MsgpIs a pointer to a struct, which is defined by the user. The defined structure should follow the following format:
struct msgbuf {    long mtype;         /* message type, must be > 0 */    char mtext[1];      /* message data */};
Where, MsgflgDetermines the features of a message. For example, by default, if there is no space in the message queue, the default message queue will be blocked. However, if the msgflg field is assigned ipc_nowait, The eagain error is returned directly.



4. read data from the Message Queue
# Include <sys/types. h> # include <sys/IPC. h> # include <sys/MSG. h> ssize_t msgrcv (INT msqid, // Message Queue identifier void * msgp, // size_t msgsz, container for receiving messages, // Message Size long msgtyp, // The Message Type int msgflg of the received message); // you can set some features when receiving the message. // return value:> 0 (data size successfully read)-1 (failed, for error messages, see errno)
Where, MsgtypeIs the acceptance priority, that is, the mtype field in the msgbuf struct. If it is set to 0, it is obtained from the first message in the message queue. If it is set to 0, it is obtained from the first message with the same message type. If it is set to 0, it is obtained from <= ABS (msgtype) the first message.
MsgflgDetermines the characteristics of a message. For example, if the size of the sent message exceeds the size of the receiving container, an error is returned by default, and errno is set to e2big. however, if msgflg is set to msg_noerror, the message is truncated according to the receiving container and a success is returned.


5. Message Queue attribute operation functions
# Include <sys/types. h> # include <sys/IPC. h> # include <sys/MSG. h> int msgctl (INT msqid, // Message Queue identifier int cmd, // struct msqid_ds * BUF ); // Message Queue attributes // return value: 0 (successful)-1 (failed. For details about the failure, see errno)
Where, CMDThe value is as follows: ipc_stat obtains the attribute information of the Message Queue. ipc_set sets the attribute information of the Message Queue. ipc_rmid deletes the message queue and returns an error to the associated read/write process. errno is set to eidrm.
Buf ParametersIs the struct pointer of the message attribute. The struct is defined as follows:
struct msqid_ds {    struct ipc_perm msg_perm;        /* Ownership and permissions */    time_t msg_stime;                /* Time of last msgsnd(2) */    time_t msg_rtime;                /* Time of last msgrcv(2) */    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(2) */    pid_t msg_lrpid;                 /* PID of last msgrcv(2) */};struct ipc_perm {    key_t __key;                      /* Key supplied to msgget(2) */    uid_t uid;                        /* Effective UID of owner */    gid_t gid;                        /* Effective GID of owner */    uid_t cuid;                       /* Effective UID of creator */    gid_t cgid;                       /* Effective GID of creator */    unsigned short mode;              /* Permissions */    unsigned short __seq;             /* Sequence number */};
The size of the message queue is in the following file:

/Proc/sys/kernel/msgmax maximum value of a single messageThe default value is 8192.
/Proc/sys/kernel/msgmnbThe maximum size of a message body is 16384 by default.
/Proc/sys/kernel/msgmniThe default number of message bodies is 16.

You can also use the msg_qbytes field to modify the total size of a message queue.


6. Shell manual deletion method
In ipcrm-Q msqid, you can also use IPCS to view the msqid corresponding to the key value 1234 (4d2) in this environment. You can delete a message queue by executing ipcrm-Q 32768.

3. Instance 1. Write Data to the Message Queue
/*************************************** * *********************************> File Name: testmsgqueuew. c> author: qiaozp> mail: [email protected]> created time: 17:15:09> step: 1. Connect to message queue 2. Read data ********************************* ***************************************/ # include <sys/types. h> # include <sys/IPC. h> # include <sys/MSG. h> # include <iostream> # include <stdio. h> # include <string. h> # include <errno. h> using namespace STD; # define key 1234 # define max_buff_size 512 typedef struct {long mtype; char mtext [max_buff_size];} _ msgbuf; int main () {// 1 create a message queue int msgid = 0; If (msgid = msgget (key_t) Key, 0666 | ipc_creat) =-1) {cout <"failed to create a message queue with a key value of [" <key <"]" <Endl; Return-1 ;}_ msgbuf Buff; // 2 write data to the Message Queue while (1) {cout <"Enter the data to be placed in the message memory:"; scanf ("% s", Buff. mtext); If (msgsnd (msgid, (void *) & buff, max_buff_size, 0) =-1) {cout <"failed to send data to the Message Queue whose key value is [" <key <"]" <Endl; Return-1 ;}if (strncasecmp (buff. mtext, "end", strlen ("end") = 0) {// Delete the Message Queue if (msgctl (msgid, ipc_rmid, null) at the end) =-1) {cout <"failed to delete message queue with key value [" <key <"]" <Endl; Return-1 ;} break;} return 0 ;}


2. read data from the Message Queue
/*************************************** * *********************************> File Name: testmsgqueuer. c> author: qiaozp> mail: [email protected]> created time: 17:15:28> step: 1. Create a message queue, 2 write data, 3 end, and exit ****************************** **************************************** **/# include <sys/types. h> # include <sys/IPC. h> # include <sys/MSG. h> # include <iostream> # include <stdio. h> # include <string. h> # include <errno. h> using namespace STD; # define key 1234 # define max_buff_size 512 typedef struct {long mtype; char mtext [max_buff_size];} _ msgbuf; int main () {// 1 create a message queue int msgid = 0; If (msgid = msgget (key_t) Key, 0666 | ipc_creat) =-1) {cout <"failed to create a message queue with a key value of [" <key <"]" <Endl; Return-1 ;}_ msgbuf Buff; // 2 write data to the Message Queue cout <"to get data from the message queue. Please input data on the server... "<Endl; while (1) {If (msgrcv (msgid, (void *) & buff, max_buff_size, 0, 0) =-1) {cout <"An error occurred while retrieving data from a message queue whose key value is [" <key <"]" <Endl; Return-1 ;} cout <"the obtained data is:" <buff. mtext <Endl; If (strncasecmp (buff. mtext, "end", strlen ("end") = 0) {cout <"quit. "<Endl; break;} return 0 ;}


Inter-process communication 05 Message Queue

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.