Message Queue for Process Communication

Source: Internet
Author: User

1. What is a message queue?
The message queue usesQueueThe data structure of the form (message linked list) is stored in the system kernel. It can be used for bidirectional data streams between customer processes and service processes. However, like semaphores and shared memory, it only communicates within the system and has no name in the system. Its content is not automatically deleted and there is no file descriptor. These shortcomings have led to the basic absence of modern process communication. Even so, today I still need to know about it.

2. Message Data Type

First, the header file <sys/msg. h> defines the data types that can be passed to the Message Queue:

Struct Msgbuf
{
Long Mtype;
Char Mtext [ 1 ];
}

Mtype refers to the type of the message. Different messages can be distinguished to identify the source of the message. For example, we set the mtype of the customer process to 1, the mtype of the service process is set to 2, so that we can implement two-way communication between the customer process and the service process. Note: msgbuf is just a template. You can use this template to customize other data structures and send them to message queues. For example:

Struct Msgbuf_custom
{
Long Mtype;
Char Name [ 256 ];
Int Age;
}

We have defined msgbuf_custom, which can transmit the name and age of the string to the message queue.

3. Related functions

(1). key_t ftok (char * fname, int ID)

Ftok () is used to generate a unique ID, which is provided to the IPC object as the key so that it can communicate with other IPC objects. Fname is the specified file name (an existing file name). The current directory is generally used, for example:

Key_t key = Ftok ( " . " , 1 ); // Set fname to the current directory. ID is the sub-serial number.

The return value is generally the index node number of the fname and the ID is added.

(2). Int msgget (key_t key, int msgflag)
Msgget is used to open or generate a message queue. The key is the key generated by the above function. The specific behavior of msgget is related to the value of msgflag:
Ipc_creat: this parameter is created if it does not exist. If it exists, it is opened.
Ipc_excl: This value must be connected to ipc_creat (through |) for reference. It is used with ipc_creat. If it does not exist, it is created. If it exists, an error-1 is returned, and the error code is eexist. The following is an encapsulated function for opening a message queue:

Int Openmsg (key_t key)
{
Int Mid;
If (Mid = Msgget (Key, ipc_creat | 0660 )) =- 1 )
{
Perror ( " Open error: " );
Exit ( 1 );
}
Return Mid;
}

Note that we have added 0660 permissions to it.

(3). Int msgsnd (INT mid, struct msgbuf * Buf, int msgsize, int msgflag );

Msgsnd () is used to send a message to the Message Queue. Mid is the result returned by the above function msgget (), Buf is the message to be sent, and msgsize is the message size, msgflag depends on the specific values:
0, then ignore.
Ipc_nowait: if the message queue is not full, the Buf will not be written, and the returned message will not cause blocking.
Below we encapsulate a function for sending a message queue:

Int Writemsg ( Int Mid, Struct Msgbuf * Mbuf)
{
Int RS;
Int Len = Sizeof ( Struct Msgbuf) - Sizeof ( Long );
If (RS = Msgsnd (MID, mbuf, Len, 0 ) =- 1 )
{
Perror ( " Write error: " );
Exit ( 1 );
}
Return RS;
}

(4). Int msgrcv (INT mid, struct msgbuf * Buf, int msgsize, long mtype, int msgflag)
Msgrcv () is used to extract mtype messages to the Buf. The value of msgflag can be:
0, ignore.
Ipc_nowait: if the message queue is empty, enomsg is returned without process blocking.
Msg_noerror: If the obtained message is greater than msgsize, only the message of msgsize is returned. If this value is set, messages will be left in the queue.
Below we encapsulate a function for sending a message queue:

Int Readmsg ( Int Mid, Long Mtype, Struct Msgbuf * Mbuf)
{
Int RS;
Int Len = Sizeof ( Struct Msgbuf) - Sizeof ( Long );

If(RS=Msgrcv (MID, mbuf, Len, mtype,0))=-1)
{
Perror ("Read is error");
Exit (1);
}
ReturnRS;
}

Using the msgflag feature, we can also check whether a message of the specified type (mtype) exists:

Int Msg_exist ( Int Mid, Long Mtype)
{
Int RS;
If (RS = Msgrcv (MID, null, 0 , Mtype, ipc_nowait )) =- 1 )
{
If (Errno = E2big)
{
Return 1 ;
} Else {
Perror ( " Exist is error " );
Exit ( 0 );
}
}
Return 0 ;
}

(5). Int msgctl (INT mid, int cmd, struct msqid_ds * BUF)
CMD can take the following values:
Ipc_stat: Extracts msqid_ds data from the Message Queue stored by the system to the Buf.
Ipc_set: resets msqid_ds data of the Message Queue stored by the system based on the Buf.
Ipc_emid: deletes the queue from the system.
The following is a function for deleting a message queue:

Void Delmsg ( Int Mid)
{
Msgctl (MID, ipc_rmid, 0 );
}

The following is a function that encapsulates the permissions used to reset a message queue:

Void Modifymsg ( Int Mid, Char * Mode)
{
Struct msqid_ds MDS;

msgctl (MID, ipc_stat, & MDS);
sscanf (mode, " % ho " , & MDS. MSG _ Perm. mode);
msgctl (MID, ipc_set, & MDS);
}

3. an instance
attachment provides an instance. After downloading, use: gcc-O msgtool. c func. c compilation.
usage :. /msgtool W 1 "codebean" // write the data "codebean" type as 1 into the Message Queue
. /msgtool R 1 // retrieve a message whose queue type is 1
. /msgtool D // Delete the 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.