Inter-process communication depth Message queue details _c language

Source: Internet
Author: User
Tags message queue mutex strlen

recently on the Hi3515 Debug QT and DVR program, found that they use Message Queuing communication between, leisure, summed up the message queue, hehe, think it easy to understand, at the same time, in the application also found a strong message queue.

About thread management (mutex and condition variables) see:Linux Thread Management Prerequisites: Resolving Mutex and conditional variables

First, the characteristics of message queues

1. Message Queuing is a linked list of messages that has a specific format that is stored in memory and identified by the message queue identifier.
2. Message Queuing allows one or more processes to write and read messages to it.
3. Pipelines and named Pipes are both advanced first-out principles for communication data.
4. Message Queuing can implement a random query of messages, and messages are not necessarily read in FIFO order, or by type of message. More advantages than FIFO.

There are currently two main types of message queues:POSIX message queues and System V message queues, and System V message queues are currently heavily used. System V message queues are persisted with the kernel and will only be deleted if the kernel is reset or manually deleted.

Second, correlation function

1. Get key value

key_t Ftok (char *pathname, int ProjId)

#include <sys/types.h>
#include <sys/ipc.h>
Parameters:
Pathname: File name (including path), usually set to current directory "." such as ProjId as ' a ', then ". A" file
ProjId: Project ID, must be a non 0 integer (0-255).

2. Create message queues
int Msgget (key_t key, int msgflag)

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
Function:
Used to create a new or open a message queue that already exists, which corresponds to the key.
Parameters:
key: The return value or Ipc_private of the function Ftok.
Msgflag:
Ipc_creat: Creates a new message queue.
IPC_EXCL: Use with Ipc_creat to return an error if the message queue to be created already exists.
Ipc_nowait: When read and write message queue requirements are not satisfied, do not block.
return value:
The call successfully returns the queue identifier, otherwise, returns-1.

In the following two cases, a new message queue is created:
1. If there is no message queue corresponding to the key value key, and the Msgflag contains the IPC_CREAT flag bit.
2, key parameter is ipc_private.

3. Message Queuing Property Control
int msgctl (int msqid, int cmd, struct msqid_ds *buf)
Function:

Various control operations are performed on message queues, and the actions are controlled by CMD.
Parameters:
Msqid:Message Queue ID, message queue identifier, which is the return value of Msgget to create a message queue.
Cmd:
Ipc_stat: Stores the current values of each element in the MSQID-related data structure into the structure pointed to by BUF.
Ipc_set: Sets the elements in the MSQID-related data structure to the corresponding values in the structure that the BUF points to.
Ipc_rmid:RemoveMessage Queuing, indicated by Msqid, deletes it from the system and destroys the relevant data structure.
BufMessage Queuing buffers
struct Msqid_ds{
struct Ipc_perm msg_perm; /* Ownership and permissions*/
time_t Msg_stime; /* Time of last msgsnd () * *
time_t Msg_rtime; /* Time of last MSGRCV () * *
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 bytesallowed in queue * *
pid_t Msg_lspid; /* PID of Last msgsnd () * *
pid_t Msg_lrpid; /* PID of Last MSGRCV () * *
};

struct Ipc_perm{
key_t key; /* Key supplied to Msgget () * *
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 Creator * *
unsigned short mode; * Permissions * *
unsigned short seq; /* Sequence Number * *
};

4. Send information to Message Queuing
    int msgsnd (int msqid,  struct MSGBUF *msgp,  size_t msgsz,  int msgflag)
#include <sys/types.h>
#include <sys/ipc.h>
# Include <sys/msg.h>
feature:

    Adds a new message to the end of the queue, sending a message to the message queue.
parameter:
     msqid: Open message Queue ID
      MSGP: The structural body pointer that holds the message.
     Msgflag: Control properties for functions.
     message structure msgbuf is:
     struct MSGBUF
    {
         long mtype;//message type
         char mtext[1];//Message text, the first address of the message data, the maximum length of this data is 8012 bar, but also to him as a structure, there are types and data, recv parsing can be.
  &NBSP;&NBSP;}
  &NBSP;&NBSP msgsz: The length of the message data.
     msgflag:
           ipc_nowait: Indicates that msgsnd immediately returns when the message queue does not have enough space to hold the message to be sent.
           0:msgsnd call blocking until the condition is satisfied. (General selection)

5. Receive information from Message Queuing
    ssize_t msgrcv (int msqid,  struct MSGBUF * msgp,  size_t msgsz,  long msgtype,  int msgflag)
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
features:

Receive messages from the queue
Parameters:
msqid: Open message Queue ID
MSGP: The structural body pointer that holds the message. The msgp-> mtype is the same as the fourth parameter.
Msgsz: The number of bytes of the message, specifying the size of the mtext.
Msgtype: The message type, the value of the message type Mtype. If 0, the first piece of information in the queue is accepted, and if less than 0, the message type is accepted that is less than the absolute value, or a message of the specified type, if greater than 0, that is the value message.
Msgflag: The control attribute of the function.
Msgflag:
Msg_noerror: If more messages are returned than Nbytes bytes, the message is truncated to the nbytes byte, and the message is not notified of the sending process.
Ipc_nowait: The calling process returns immediately. Returns 1 if no message is received.
The 0:MSGRCV call blocks until the condition is satisfied.
After a message has been successfully read, the message in the queue is deleted.

Third, related examples

Example 1: Simple transceiver test for Message Queuing
#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>

struct msg_buf{
int mtype;//Message Type
Char data[255];//data
};

int main(int argc, char *argv[])
{
key_t key;
int msgid;
int ret;
struct MSG_BUF msgbuf;
//Get key value
key = Ftok (".", ' a ');
printf ("key = [%x]\n", key);

       //Create message queues
        MsgId = msgget (key,  ipc_creat|0666); /* through file corresponding */
      if (MsgId = = 1)
      {
            printf ("creat error\n");
            return-1;
      }

//To send "test data" to Message Queuing in a non-blocking manner, in the current process type
Msgbuf.mtype = getpid ();
strcpy (msgbuf.data, "test data");
ret = msgsnd (MsgId, &msgbuf, sizeof (Msgbuf.data), ipc_nowait);
if (ret = 1)
{
printf ("Send Message err\n");
return-1;
}

//Receive data in a non-blocking manner
memset (&msgbuf, 0, sizeof (MSGBUF));
     ret = MSGRCV (msgid,  &msgbuf,  sizeof ( Msgbuf.data),   getpid (),   ipc_nowait);
  &NBSP;&NBSP;&NBSP;&NBSP;IF (ret = 1)
      {
        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PRINTF ("Receive Message err\n");
            return-1;
  &NBSP;&NBSP;&NBSP;&NBSP;}
      printf ("Receive msg = [%s]\n",  msgbuf.data);
      return 0;
}
Example 2: Inter-process Message Queuing communication
#include <stdio.h>
#include <stdlib.h>
# Include <unistd.h>
#include <sys/ipc.h>
#include <string.h>
#include <signal.h>

struct msgbuf{
int mtype;
Char mtext[100];
};

int main(void)
{
key_t key;
pid_t pid;
int msgid;
struct msgbuf msg;

Key=ftok (".", 0x01);
if ((msgid = Msgget (key, ipc_creat|0666)) <0)
     {
perror ("Msgget error");
exit (1);
  }

//Create a process
if ((pid = fork ()) < 0)
{
Perror ("fork Error");
Exit (1);
}
 //Child process receipt information
else if (pid==0)
{
while (1)
{
memset (msg.mtext, 0, 100);
MSGRCV (MsgId, &msg, 2, 0); Receive the MSG from 2
printf ("\receive:%s\n:", Msg.mtext);
Fflush (stdout);
}
Exit (0);
}
//parent process Send Message
Else
{
while (1)
{
memset (msg.mtext, 0, 100);
printf ("Father:");
Fgets (Msg.mtext, stdin);
if (strncmp ("Bye", Msg.mtext, 3) ==0)//If the first 3 characters are bye, exit
{
Kill (PID, SIGSTOP);
Exit (1);
              
                          msg.mtype= 1 //send to 1
                        msg.mtext[strlen (Msg.mtext) -1]= ' ";
                         msgsnd (MsgId, &msg, strlen (msg.mtext) +1, 0);
                }
       }

return 0;
}

The disadvantage of this procedure is: There is no charge, there is no hair. You can create 2 threads in each of these 2 processes, respectively responsible for receiving and sending, to complete interprocess communication.

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.