Linux interprocess communication------Message Queuing

Source: Internet
Author: User
Tags message queue strcmp

A message queue is a linked list of messages. You can think of a message as a record, with a specific format and a specific priority. A process that has write permission to a message queue can add new messages to it by a certain rule, and a process that has read access to a message queue can read messages from the message queue.

Message Queuing and shared memory like Message Queuing it allows one or more processes to write messages to it, and one or more processes write to it. Message Queuing exists in the system kernel, and the number of messages is limited by the system. Let's take a look at the function for Message Queuing.

Linux Message Queuing (queue) is essentially a linked list that has a message queue identifier (queue ID). Msgget Create a new queue or open an existing queue; msgsnd adds a new message to the end of the queue; MSGRCV the message from the queue, the message is not necessarily followed by FIFO, or the Message Type field can be taken.


System V mechanism

Identifiers (DES) and Keys (key):
Message queues, semaphores, and shared buckets belong to the IPC structure in the kernel, and they are all described by identifiers. This identifier is a non-negative integer, unlike a file descriptor, that is created without reusing an integer that is recycled by deleting it, but each time +1, until the integer maximum is turned to 0.
The identifier is the internal name of the IPC object, and its external name is key (the key), and its base type is key_t, which is defined as a long integer in the header file. The key is transformed from the kernel into an identifier.

Message Queuing status Msqid_ds:
Each message queue has a MSQID_DS structure associated with it:

struct msqid_ds{struct msqid_ds {struct ipc_perm msg_perm;struct msg *msg_first;/* First message on queue,unused */struct MSG *msg_last; /* Last message in queue,unused */__kernel_time_t msg_stime; /* Last msgsnd time */__kernel_time_t msg_rtime; /* Last MSGRCV time */__kernel_time_t msg_ctime; /* Last change time */unsigned long msg_lcbytes; /* reuse junk fields for + bit */unsigned long msg_lqbytes; /* ditto */unsigned short msg_cbytes; /* Current number of bytes in queue */unsigned short msg_qnum; /* Number of messages in queue */unsigned short msg_qbytes; /* max number of bytes on queue */__kernel_ipc_pid_t msg_lspid; /* pid of last msgsnd */__kernel_ipc_pid_t msg_lrpid; /* Last receive PID */};


functionHeader file:

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

1. Create a new message queue or get an existing message queue
Prototype: int msgget (key_t key, int msgflg);
Parameters:

key: Can be thought of as a port number, or it can be generated by the function Ftok.

The msgflg:ipc_creat value, which, if there is no queue, creates one and returns a new identifier, or returns the original identifier if it already exists. A IPC_EXCL value that returns 1 if there is no queue, or 0 if it already exists.

Example 1:

#include <stdio.h> #include <stdlib.h> #include <sys/msg.h> #define MYMSG_KEY 6666int Main (int argc, Char *argv[]) {        int msgid;        Msgid=msgget (Ftok (".", +), Ipc_creat | 0644);        Msgid=msg (Mymsg_key,ipc_creat | 0644);        printf ("msgid=%d\n", MsgId);        if (msgid==-1)        {                perror ("Msgget error:");                Exit (exit_failure);        }         return 0;}

parsing:we can use IPCS-Q to see if the creation was successful. Delete with the ipcrm–q msgid number.


2. Read/write messages to the queue
Prototype:
MSGRCV messages from the queue: ssize_t msgrcv (int msqid, void *msgp, size_t msgsz, long Msgtyp, int msgflg);
MSGSND put data into Message Queuing: int msgsnd (int msqid, const void *MSGP, size_t msgsz, int msgflg);
Parameters:
MSQID: Message Queue identification code
MSGP: A pointer to the message buffer, which is used to temporarily store messages sent and received, is a common, user-definable structure, as follows:
<span style= "FONT-SIZE:14PX;" >struct msgstru{    long mtype;//greater than 0    char mtext[512];}; </span>
MSGSZ: The size of the message.
Msgtyp: The message pattern read from within the message queue. A value of zero indicates that all messages in the message queue will be read.
MSGFLG: Used to indicate the action that the core program should take if the queue has no data. If the MSGFLG and constant ipc_nowait are pooled, then if the message queue is full at msgsnd () execution, then MSGSND () will not block, and will immediately return-1, if the MSGRCV () is performed, then when the message queue is empty, do not wait for the immediate return-1, and set the error code to enomsg. When MSGFLG is 0 o'clock, msgsnd () and MSGRCV () take a blocking wait processing mode when the queue is full or empty. Example 2:
#include <stdio.h> #include <stdlib.h> #include <sys/msg.h> #include <string.h> #define Mymsg_      KEY 6666 struct MYMESG {long mtype; /* Positive Message type */char mtext[512]; /* message data, of length nbytes */};        int main (int argc, char *argv[]) {int msgid,msgsend_ret;        Char buf[25];        struct MYMESG msg_send;        Msgid=msgget (Ftok (".", +), Ipc_creat | 0644);        Msgid=msg (Mymsg_key,ipc_creat | 0644);        printf ("msgid=%d\n", MsgId);                if (msgid==-1) {perror ("Msgget error:");        Exit (Exit_failure);        }//write messages to msg queue msg_send.mtype=1;        printf ("Enter a message:\n");        Gets (BUF);        strcpy (MSG_SEND.MTEXT,BUF);        Msgsend_ret=msgsnd (Msgid,&msg_send,strlen (Msg_send.mtext) +1,0);                if (msgsend_ret==-1) {perror ("Msgget error:");        Exit (Exit_failure); } return 0;}
Parse: Run once, after writing the message, the number of messages is 1, and then run once,we can see that the number of messages is2.
Example 3:
#include <stdio.h> #include <stdlib.h> #include <sys/msg.h> #include <string.h> #define Mymsg_      KEY 6666 struct MYMESG {long mtype; /* Positive Message type */char mtext[512]; /* message data, of length nbytes */};        int main (int argc, char *argv[]) {int msgid,msgsend_ret;        Char buf[25];        struct MYMESG msg_send;        Msgid=msgget (Ftok (".", +), Ipc_creat | 0644);        Msgid=msg (Mymsg_key,ipc_creat | 0644);       printf ("msgid=%d\n", MsgId);                if (msgid==-1) {perror ("Msgget error:");        Exit (Exit_failure);        }//write messages to msg queue/* 0 msg_send.mtype=1;        printf ("Enter a message:\n");        Gets (BUF);        strcpy (MSG_SEND.MTEXT,BUF);        Msgsend_ret=msgsnd (Msgid,&msg_send,strlen (Msg_send.mtext) +1,0);                if (msgsend_ret==-1) {perror ("Msgget error:");        Exit (Exit_failure); }*///read mseeags from MSG queue int Msgrcv_ret;        struct MYMESG mymsgrece; MSGRCV_RET=MSGRCV (msgid,&mymsgrece, sizeof (struct MYMESG)-sizeof (long), 1,0);//The type of read message is 1 and the length is sizeof (struct        MYMESG)-sizeof (long) put the read//message into the structure of mymsgrece.                if (msgrcv_ret==-1) {perror ("MSGRCV error:");        Exit (Exit_failure);          } printf ("Received msg from queue:%s\n", Mymsgrece.mtext); return 0;}
Resolution: After 2 runs, the data in the message queue is removed.

3. Set Message Queuing properties
Prototype: int msgctl (int msgqid, int cmd, struct msqid_ds *buf);
Parameters: The MSGCTL system invokes a CMD operation on the message queue identified by the msgqid, and the system defines 3 cmd operations: Ipc_stat, Ipc_set, Ipc_rmid
Ipc_stat: This command is used to obtain the MSQID_DS data structure for the message queue and save it to the BUF specified address space.
Ipc_set: The command is used to set the properties of the message queue, and the properties to be set are stored in BUF.
Ipc_rmid: Removes the MSQID identity message queue from the kernel.
Example 4
//send.c#include<stdio.h> #include <stdlib.h> #include <sys/msg.h>#      include<string.h> #define Mymsg_key 6666 struct MYMESG {long mtype; /* Positive Message type */char mtext[512]; /* message data, of length nbytes */};    int main () {int msgid,msgsend;    struct MYMESG mymsgsend;    Msgid=msgget (mymsg_key,ipc_creat|0644);    printf ("msgid=%d\n", MsgId);       if (msgid==-1) {perror ("Msgget error:");    Exit (Exit_failure);    } mymsgsend.mtype=1;       while (1) {printf ("Enter a type and a msg use to send: \ n");       scanf ("%d%s", &mymsgsend.mtype,mymsgsend.mtext);       Msgsend=msgsnd (Msgid,&mymsgsend,strlen (Mymsgsend.mtext) +1,0);           if (msgsend==-1) {perror ("Msgget error:");       Exit (Exit_failure);     } if (strcmp (Mymsgsend.mtext, "exit") ==0) break; } return 0;} 
//recv.c#include<stdlib.h> #include <sys/msg.h> #define Mymsg_key 6666      struct MYMESG {long mtype; /* Positive Message type */char mtext[512];  /* message data, of length nbytes */};    int main () {int msgid,msgrcv_ret,msgctl_ret;    struct MYMESG mymsgrece;    Msgid=msgget (Mymsg_key, ipc_creat|0644);    printf ("msgid=%d\n", MsgId);       if (msgid==-1) {perror ("Msgget error:");    Exit (Exit_failure);       } while (1) {scanf ("%d", &mymsgrece.mtype);       MSGRCV_RET=MSGRCV (msgid,&mymsgrece,512,mymsgrece.mtype,0);           if (msgrcv_ret==-1) {perror ("MSGRCV error:");       Exit (Exit_failure);          } if (strcmp (Mymsgrece.mtext, "exit") ==0) break;    printf ("Received msg:%s\n", Mymsgrece.mtext);    } msgctl_ret=msgctl (msgid,ipc_rmid,0);       if (msgctl_ret==-1) {perror ("MSGRCV error:");    Exit (Exit_failure); } return 0;} 

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

Linux interprocess communication------Message Queuing

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.