System V Message Queuing for inter-process communication between Linux

Source: Internet
Author: User
Tags message queue

Tag: Generate string Child position buffer + RMI \ n mil

a message queue is a list of messages that have a specific format and a specific priority. A process that has write access to Message Queuing can add a new message to a certain rule, and a process that has Read permission on the message queue can read the message from the message queue. This enables communication between the two processes.
Header file and function prototypes for System V Message Queuing:
#include <sys/msg.h>
1. Create a new message queue and get a message queue that already exists

prototype: int msgget (key_t key, int msgflg);return Value: A non-negative return was successfully returned with an error of -1.Parameters:key: Must be unique, can be customized such as "#define KEY 1234", can also 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. 2. Write messages and read messages to Message Queuing:Prototypes:writes data to the message queue: int msgsnd (int msqid, const void *MSGP, size_t msgsz, int msgflg);return value: Successfully returned 0, error returned -1.read message from message queue: ssize_t MSGRCV (int msqid, void *msgp, size_t msgsz, long Msgtyp, int msgflg);return Value: The number of bytes read was successfully returned, and an error returned -1.Parameters:msqid: The message queue identifier returned from Msgget.MSGP: A pointer to the message buffer, which is used to temporarily store messages sent and received, is a generic, user-definable structure, in the following form:struct msgstru{long mtype;//greater than 0Char mtext[1];       }MSGSZ: The size of the message, which is the length of the message that the MSGP points to, note the length of the message, not the length of the entire structure, that is, MSGSZ is not the length of the Msgtyp of the long integer message-type member variable. 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.

3. Control Message Queuing:prototype: int msgctl (int msgqid, int cmd, struct msqid_ds *buf);return value: Successfully returned 0, error returned-1Parameters: 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: Returns the MSQID_DS data structure corresponding to the specified message queue with the BUF parameter and saves 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: The message queue for the msqid identity is removed from the system kernel, and any messages currently on the message queue are discarded, and for that command, the third parameter, "struct Msqid_ds *buf", is ignored.  code Example:Send program SYSTEMV_MSG_SEND.C
  1. /*systemv_msg_send.c*/
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/ipc.h>
  7. #include <sys/msg.h>
  8. #include <errno.h>
  9. #define Msgkey 4321
  10. #define MAX_SIZE 1024
  11. struct MSGSTRU
  12. {
  13. Long Msgtype;
  14. Char Msgtext[max_size];
  15. };
  16. Main ()
  17. {
  18. struct Msgstru msgs;
  19. int msg_type;
  20. Char str[256];
  21. int ret_value;
  22. int msqid;
  23. Msqid=msgget (MSGKEY,IPC_EXCL); /* Check if Message Queuing exists */
  24. if (Msqid < 0) {
  25. Msqid = Msgget (msgkey,ipc_creat|0666);/* Create message Queue */
  26. if (Msqid <0) {
  27. printf ("Failed to create MSQ | errno=%d [%s]\n], Errno,strerror (errno));
  28. Exit (-1);
  29. }
  30. }
  31. while (1) {
  32. printf ("Input message type (end:0):");
  33. scanf ("%d", &msg_type);
  34. if (Msg_type = = 0)
  35. Break
  36. printf ("Input message to be sent:");
  37. scanf ("%s", str);
  38. Msgs.msgtype = Msg_type;
  39. strcpy (Msgs.msgtext, str);
  40. /* Send Message Queue */
  41. Ret_value = msgsnd (msqid,&msgs,max_size,ipc_nowait);
  42. if (Ret_value < 0) {
  43. printf ("msgsnd () write msg failed,errno=%d[%s]\n", Errno,strerror (errno));
  44. Exit (-1);
  45. }
  46. }
  47. Msgctl (msqid,ipc_rmid,0); Delete Message Queuing
  48. }
Copy CodeReceiving program systemv_msg_receive.c
  1. /*SYSTEMV_MSG_RECEIVE.C * *
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/ipc.h>
  7. #include <sys/msg.h>
  8. #include <errno.h>
  9. #define Msgkey 4321
  10. #define MAX_SIZE 1024
  11. struct MSGSTRU
  12. {
  13. Long Msgtype;
  14. Char Msgtext[max_size];
  15. };
  16. /* Child process, listening for Message Queuing */
  17. void Childproc () {
  18. struct Msgstru msgs;
  19. int msgid,ret_value;
  20. Char str[256];
  21. while (1) {
  22. MsgId = Msgget (MSGKEY,IPC_EXCL);/* check if Message Queuing exists */
  23. if (MsgId < 0) {
  24. printf ("Msq not existed! errno=%d [%s]\n], Errno,strerror (errno));
  25. Sleep (2);
  26. Continue
  27. }
  28. /* Receive Message Queuing */
  29. Ret_value = MSGRCV (msgid,&msgs,max_size,0,0);
  30. printf ("Receive data=[%s],ret_value=[%d], pid=[%d]\n", Msgs.msgtext,ret_value,getpid ());
  31. }
  32. Return
  33. }
  34. void Main ()
  35. {
  36. int i,cpid;
  37. /* Create 5 child process */
  38. for (i=0;i<5;i++) {
  39. Cpid = fork ();
  40. if (Cpid < 0)
  41. printf ("fork failed\n");
  42. else if (cpid ==0)/*child process*/
  43. Childproc ();
  44. }
  45. }
Copy CodeSend program run:$./sendinput Message type (end:0): 1input message to be sent:123input Message type (end:0):input message to be sent:456input Message type (end:0): $input message to be SENT:ABCDEFGinput Message type (end:0):

Receive program run Result: $./receivereceive data=[123],ret_value=[1024], pid=[15586]receive data=[456],ret_value=[1024], pid=[15584 ]receive data=[abcdefg],ret_value=[1024], pid=[15583]

System V Message Queuing for inter-process communication between Linux

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.