Message communication of process communication

Source: Internet
Author: User
Tags assert message queue


Message communication messages


Messages are an important way of interprocess communication, usually made up of both the client and server side. The server creates a message queue with a specific key value, populates the message queue with the message and data type to be sent according to the agreed message format. On the client side, the corresponding data is received according to the known key value and the specified location type encoding. Instead of maintaining Message Queuing, you can focus on data transfer in a way that shares memory, but it is less flexible for applications that need to share or transfer more complex data structures.


Important function groups for message communication include:


Intmsgget (key_t key, int msgflg);


The Msgget () system call returns the system V message Queue identifierassociated with the value of the key argument. A

New MessageQueue is created if key have the value ipc_private or key isn ' tipc_private, no message queue with the given key

Key Exists,and Ipc_creat is specified in MSGFLG.


If msgflgspecifies both Ipc_creat and IPC_EXCL and a message queue alreadyexists for key, then Msgget () fails with errno

Set Toeexist. (This was analogous to the effect of the combination o_creat| O_EXCL for Open (2).)


Uponcreation, the least significant bits of the argument MSGFLG definethe permissions of the message queue. These per‐

Mission BITS has the same format and semantics as the permissions specified forthe mode argument of open (2). (The Exe‐

Cutepermissions is not used.)


intmsgsnd (int msqid, const void *MSGP, size_t msgsz, int msgflg);


SSIZE_TMSGRCV (int msqid, void *msgp, size_t msgsz, long MSGTYP,INTMSGFLG);


DESCRIPTION

The msgsnd () and MSGRCV () system calls is used, respectively, to send Messagesto, and receive messages from, a system V

MessageQueue. The calling process must has the Write permission on the MessageQueue in order to send a message, and read

Permission toreceive a message.


The msgpargument is a pointer to a caller-defined structure of the Followinggeneral form:


Structmsgbuf {

Longmtype; /* Message type, must be > 0 */

CHARMTEXT[1]; /* Message Data */

};


The Mtext field is an array (or all structure) whose size is specified Bymsgsz, a nonnegative integer value. Messages

of zerolength (i.e., no mtext field) is permitted.   The Mtype field musthave a strictly positive integer value. This

Value can beused by the receiving process for message selection (see Thedescription of MSGRCV () below).


Intmsgctl (int msqid, int cmd, struct msqid_ds *buf);


DESCRIPTION

Msgctl () performs the control operation specified by cmd on the System vmessage a queue with identifier msqid.


The MSQID_DSDATA structure is defined in <sys/msg.h> as follows:


Structmsqid_ds {

Structipc_perm Msg_perm; /* Ownership and Permissions */

time_t Msg_stime; /* Time of Last msgsnd (2) */

time_t Msg_rtime; /* Time of Last MSGRCV (2) */

time_t Msg_ctime; /* Time of last change */

Unsignedlong __msg_cbytes; /* Current number of bytes in

Queue (nonstandard) */

Msgqnum_t Msg_qnum; /* Current number of messages

Inqueue * *

Msglen_t msg_qbytes; /* Maximum number of bytes

Allowedin Queue * *

pid_t Msg_lspid; /* PID of Last MSGSND (2) */

pid_t Msg_lrpid; /* PID of Last MSGRCV (2) */

};


The ipc_permstructure is defined as follows (the highlighted fields are settableusing Ipc_set):


Structipc_perm {

key_t __key; /* Key supplied to Msgget (2) */

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 of Creator */

Unsignedshort mode; /* Permissions */

Unsignedshort __seq; /* Sequence Number */

};


Valid valuesfor cmd is:


Ipc_stat

Copyinformation from the kernel data structure associated and msqid intothe Msqid_ds structure pointed to by BUF.

Thecaller must has Read permission on the message queue.


Ipc_set

Writethe values of some members of the MSQID_DS structure pointed to bybuf to the kernel data structure associated

With the message queue, updating also its msg_ctime member. Thefollowing members of the structure is updated:

Msg_qbytes,msg_perm.uid, Msg_perm.gid, and (the least significant 9 bits of) Msg_perm.mode. The effective UID of

The calling process must match the owner (Msg_perm.uid) or creator (MSG_PERM.CUID) of the message queue, or the

Callermust be privileged. Appropriate privilege (Linux:thecap_sys_resource capability) is required to raise the

Msg_qbytesvalue beyond the system parameter MSGMNB.


Ipc_rmid

Immediately Remove the message queue, awakening all waiting Reader and writerprocesses (with an error return and

Errnoset to EIDRM). The calling process must has appropriate privilegesor its effective user ID must is either

That ofthe creator or owner of the message queue. The third argument Tomsgctl () is a ignored in this case.


Ipc_info (linux-specific)

Return information about System-wide message queue limits and parameters inthe structure pointed to by BUF. This

Structureis of type Msginfo (thus, a cast is required), defined in <sys/msg.h> if the _gnu_source feature test

Macro isdefined:


Structmsginfo {

Intmsgpool; /* Size in kibibytes of buffer pool

Usedto hold message data;

Unusedwithin Kernel */

Intmsgmap; /* Maximum number of entries in message

map;unused within kernel * *

Intmsgmax; /* Maximum number of bytes that can be

Writtenin a single message * *

INTMSGMNB; /* Maximum number of bytes that can be

Writtento queue; Used to initialize

Msg_qbytesduring Queue Creation

(Msgget (2)) */

Intmsgmni; /* Maximum number of message queues */

INTMSGSSZ; /* Message segment size;

Unusedwithin Kernel */

INTMSGTQL; /* Maximum number of messages on all queues

Insystem; Unused within kernel * *

unsignedshort int msgseg;

/*maximum number of segments;

Unusedwithin Kernel */

};


Themsgmni, Msgmax, and MSGMNB settings can be changed Via/proc files ofthe same name; See proc (5) for details.


Msg_info (linux-specific)

Return a MSGINFO structure containing the same information as Foripc_info, except that the following fields is

Returnedwith information about system resources consumed by message queues:the msgpool Field returns the number of

Message queues that currently exist on the system; The Msgmap fieldreturns The total number of messages in all

Queueson the system; And the MSGTQL field returns the total number of Bytesin all messages in all queues on the

System.


Msg_stat (linux-specific)

Return a MSQID_DS structure as for Ipc_stat. However, the Msqid argument isnot a queue identifier, but instead an

Indexinto the kernel ' s internal array that maintains information about allmessage queues on the system.


ReturnValue

On Success,ipc_stat, Ipc_set, and Ipc_rmid return 0. A successful Ipc_info ormsg_info operation returns the index of the

Highest usedentry in the kernel ' s internal arrays recording information about allmessage queues. (This information can

Used withrepeated Msg_stat Operations to obtain information on all Queueson the system.) A successful Msg_stat opera‐

tion returnsthe identifier of the queue whose index is given in msqid.


On error, -1is returned with errno indicating the error.


The dependent header files include:

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>


The following is an example of a specific service-side and client-based code that is available for message communication:


Service side: TEST_MSG_SVC.C

#include <stdio.h>

#include <assert.h>

#include <inttypes.h>


#include <string.h>

#include <stdlib.h>

#include <errno.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/stat.h>

#include <sys/msg.h>


#defineMSG_FILE "Test_msg_clnt"

#defineBUFFER 255

#definePERM s_irusr| S_iwusr


Structmsgtype {

Longmtype;

CHARBUFFER[BUFFER+1];

};


Intmain ()

{

Structmsgtype msg;

Key_tkey;

Intmsgid;

if ((Key=ftok (Msg_file, ' a ')) ==-1)

{

{

fprintf (stderr, "Creatkey error:%s\a\n", Strerror (errno));

Exit (1);

}

if (Msgid=msgget (key,perm| Ipc_creat| IPC_EXCL)) ==-1)

if (Msgid=msgget (key,perm| IPC_EXCL)) ==-1)

{

fprintf (stderr, "Creatmessage error:%s\a\n", Strerror (errno));

Exit (1);

}

while (1)

{

MSGRCV (Msgid,&msg,sizeof (Structmsgtype), 1,0);

fprintf (stderr, "serverreceive:%s\n", Msg.buffer);

msg.mtype=2;

Msgsnd (Msgid,&msg,sizeof (Structmsgtype), 0);

memcpy (Msg.buffer, "Hello", strlen ("Hello") + 1);

msg.mtype=2;

Msgsnd (Msgid,&msg,sizeof (Structmsgtype), 0);

}

Exit (0);

}


Client: test_msg_clnt.c:

#include <stdio.h>

#include <assert.h>

#include <inttypes.h>


#include <string.h>

#include <stdlib.h>

#include <errno.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/stat.h>

#include <sys/msg.h>


#defineMSG_FILE "Test_msg_clnt"

#defineBUFFER 255

#definePERM s_irusr| S_iwusr


Structmsgtype {

Longmtype;

CHARBUFFER[BUFFER+1];

};


Intmain (int Argc,char **argv)

{

Structmsgtype msg;

Key_tkey;

Intmsgid;


if (argc!=2)

{

fprintf (stderr, "usage:%sstring\n\a", argv[0]);

Exit (1);

}

if ((Key=ftok (Msg_file, ' a ')) ==-1)

{

fprintf (stderr, "Creatkey error:%s\a\n", Strerror (errno));

Exit (1);

}

if ((Msgid=msgget (key,perm)) ==-1)

{

fprintf (stderr, "Creatmessage error:%s\a\n", Strerror (errno));

Exit (1);

}

msg.mtype=1;

strncpy (Msg.buffer,argv[1],buffer);

Msgsnd (Msgid,&msg,sizeof (Structmsgtype), 0);

memset (&msg, ' n ', sizeof (Structmsgtype));

MSGRCV (Msgid,&msg,sizeof (Structmsgtype), 2,0);

fprintf (stdout, "clientreceive:%s\n", Msg.buffer);

MSGRCV (Msgid,&msg,sizeof (Structmsgtype), 2,0);

fprintf (stdout, "clientreceive:%s\n", Msg.buffer);


Exit (0);

}


Compile run and its results:

[Email protected]testcases]$ gcc-o test_msg_svc test_msg_svc.c

[Email protected]testcases]$ gcc-o test_msg_clnt test_msg_clnt.c

[Email protected]testcases]$./test_msg_svc

Serverreceive:hahi

Serverreceive:gdluck

[[Email protected]testcases]$./TEST_MSG_CLNT Hahi

Clientreceive:hahi

Clientreceive:hello

[[Email protected]testcases]$./TEST_MSG_CLNT Gdluck

Clientreceive:gdluck

Clientreceive:hello


This article is from the "Store Chef" blog, so be sure to keep this source http://xiamachao.blog.51cto.com/10580956/1793985

Message communication of process 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.