Linux inter-process communication: Message Queue

Source: Internet
Author: User

In Linux, a message queue is essentially a linked list with a message queue ID ). msgget creates a new queue or opens an existing queue. msgsnd adds a new message to the end of the queue. msgrcv retrieves a message from the queue, which does not necessarily follow FIFO, you can also retrieve messages based on the Message Type field.

 

1. identifier (DES) and key (key ):

Message queues, semaphores, and shared storage segments all belong to the IPC structure in the kernel. They are described by identifiers. this identifier is a non-negative integer. Unlike the file descriptor, it is not used to delete the recycled integer at the time of creation. Instead, each time it is plus 1, until the maximum integer value is 0.

The identifier is the internal name of the IPC object, and its external name is the key (key). Its basic type is key_t. In the header file <sys/types. h> is defined as a long integer. the key is changed from the kernel to the identifier.

2. Message Queue status msqid_ds:

Each message queue has a msqid_ds structure associated with it:

Struct msqid_ds
...{
Struct ipc_perm msg_perm;/** // * access */
Msgqnum_t msg_qnum;/** // * # of messages on queue */
Msglen_t msg_qbytes;/** // * max # of bytes on queue */
Pid_t msg_lspid;/** // * PID of last msgsnd ()*/
Pid_t msg_lrpid;/** // * PID of last msgrcv ()*/
Time_t msg_stime;/** // * Last-msgsnd () time */
Time_t msg_rtime;/** // * Last-msgrcv () time */
Time_t msg_ctime;/** // * Last-change time */
...
...
...
};

 

3. A key is generated by the path name and Project ID:

If the customer process and server process recognize a path name and Project ID (0 ~ And then call ftok to convert the two values into a key.

  • Prototype: key_t ftok (const char * path, int ID );
  • Header file: <sys/IPC. h>
  • Returned value: Key is returned if the request is successful, and (key_t)-1 if an error occurs.
  • Parameter: The Path parameter must reference an existing file. When a key is generated, only the low 8 bits of the ID parameter are used.
  • NOTE: If two pathnames reference two different files, calling ftok for these two pathnames usually returns different keys. however, because the I node number and key are usually stored in long integers, information may be lost when a key is created. this means that if the same Project ID is used, the two pathnames of different files may generate the same key. the function works in the following way:
    • Obtains its stat structure based on the given path name.
    • Extract some st_dev and st_ino fields from the structure and combine them with the Project ID.

4. Create/open a message queue:

Msgget can create a new queue or open an existing queue.

  • Prototype: int msgget (key_t key, int flag );
  • Header file: <sys/msg. h>
  • Returned value: if the message queue is successful, the Message Queue ID is returned. If an error occurs, the Message Queue ID is returned.
  • Parameters:
    • Key: the key value of the message queue.
    • Flag: flag.
  • Note:
    • There are two ways to create a queue:
      • The key is ipc_private.
      • The key is not currently combined with the IPC structure of a specific type, and the ipc_creat bit is specified in the flag.
    • Initialize msqid_ds members:
      • In ipc_perm, the mode member is set by flag.
      • Msg_qnum, msg_lspid, msg_lrpid, msg_stime, and msg_rtime are both set to 0.
      • Msg_ctime is set to the current time.
      • Msg_qbytes is set as the system limit value.

5. Message Queue waste bin function:

Similar to the ioctl function in the driver, msgctl can perform multiple operations on message queues.

  • Prototype: int msgctl (INT msqid, int cmd, struct msgqid_ds * BUF );
  • Header file: <sys/msg. h>
  • Return Value: 0 is returned if the request is successful, and-1 is returned if an error occurs.
  • Parameter: cmd parameter indicates the command to be executed on the queue specified by msqid:
    • Ipc_stat: obtains the msqid_ds structure of the queue and stores it in the structure pointed to by the Buf.
    • Ipc_set: Set msg_perm.uid, msg_perm.gid, msg_perm.mode, and msg_qbytes in the queue-related structure based on the value pointed by the Buf. This command can be executed only by the following two processes:
      • The valid user ID is msg_perm.cuid or msg_per.uid.
      • Processes with super user privileges.
    • Ipc_rmid: deletes the Message Queue from the system and all data in the queue. The execution permission is the same as above.

6. Put data in the message queue:

Call msgsnd to put the data in the message queue.

  • Prototype: int msgsnd (INT msqid, const void * PTR, size_t nbytes, int flag );
  • Header file: <sys/msg. h>
  • Return Value: 0 is returned if the request is successful, and-1 is returned if an error occurs.
  • Note: You can define a message structure with a type in the structure so that messages can be acquired in a non-first-in-first-out order. when msgsnd is returned successfully, the msqid_ds structure related to the message queue is updated to indicate the ID of the called process (msg_lsqid) and the time (msg_stime) for the call ), and indicates that a message (msg_qnum) is added to the queue ).

7. retrieve messages from the message queue:

Call msgrcv to retrieve messages from the message queue.

  • Prototype: ssize_t msgrcv (INT msqid, void * PTR, size_t nbytes, long type, int flag );
  • Header file: <sys/msg. h>
  • Return Value: if the message succeeds, the length of the Data part of the message is returned. If an error occurs, the value-1 is returned.
  • Parameters:
    • PTR: point to a long integer (the returned message type is stored in it), followed by a buffer that stores the actual message data.
    • Nbytes: the length of the data buffer. If the returned message is greater than nbytes and msg_noerror is set in the flag, the message is truncated.
    • Type:
      • Type = 0: return the first message in the queue.
      • Type> 0: return the first message of type in the queue.
      • Type <0: return the message whose type value is smaller than or equal to the absolute value of type in the queue. If there are several messages, the message with the minimum type value is obtained.
  • Note: When msgrcv is returned successfully, the msqid_ds structure related to the message queue is updated to indicate the caller's process ID (msg_lrpid) and call time (msg_rtime) and the number of messages in the queue (msg_qnum) minus 1.

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.