Linux Process Communication (System V) Section 3 ------ & gt; msg queue Message queue

Source: Internet
Author: User
Tags posix superuser permission

I. Introduction There are two main types of Message Queues: POSIX message queues and System V message queues. System V message queues are currently widely used. Considering the portability of applications, newly developed applications should use POSIX message queues whenever possible. Message Queue is a data structure created by the kernel and is identified! For processes with read and write permissions, You can implement communication between different processes by reading and writing shared message processes! About the data structure of Message Queue: # include <sys/msg. h> structmsqid_ds //!> Msg queue id d (message queue status descriptor) {structipc_perm msg_perm; //!> Read and Write perms structmsg * msg_first; //!> The first msg in the queue. For memory storage, it is meaningless for users to use structmsg * msg_last; //!> The last msg in the queue, for memory storage, does not make sense for users to use msglen_t msg_cbytes; //!> Bytes msgunum_t msg_qnum in the current queue; //!> Message msglen_t msg_qbytes in the current queue; //!> Maximum allowed bytes pid_t msg_lspid in the queue; //!> The last pid pid_t msg_lrpid that sends msg; //!> The last pid time_t msg_stime that receives msg; //!> The last msg sending time time_t msg_rtime; //!> The last msg received time time_t msg_ctime; //!> Last msg control time (time of last magctl ()}; creation of Message Queue: function ---> msgget (): you can create or access an existing queue # include <sys/types. h> # include <sys/ipc. h> # include <sys/msg. h> int msgget (key_t key, int flag); //!> The return value is the operation handle //!> The key can be the return value of the ftok () function or IPC_PRIVATE //!> Flag is also a read/write permission (generally IPC_CREAT or IPC_CREAT | IPC_EXCL). Note that the initialization parameters of msqid_ds after a created queue are: the uid and cuid of msg_perm are valid user IDs of the current process; gid and cgid are the valid group IDs of the current process msg_ctime is the current time msg_qbytes: The remaining values of the system limit value are 0 operations on the queue: >>>> int msgsnd (int msqid, const void * ptr, size_t mbytes, int flag); //!> Parameter: returned value of msqid: msgget (); ptr: Is a struct pointer structmsgbuf {long mtype; char mtext [1]}; //!> Flag: can be specified as: IPC_NOWAIT ,... >>>>> Int msgrcv (int msqid, void * ptr, size_t nbytes, long type, int flag); //!> Parameter: ptr; storage location of the received message //!> Type: the type of the message to be obtained from the queue = 0: The first message is returned;> 0: the first message of type is returned; <0: return the first message with the smallest type value in the message with the type value less than or equal to the absolute value of the type parameter >>>> int msgctl (int msqid, int cmd, struct msqid_ds * buff ); you can perform the following operations: IPC_RMID: to delete all data in a specified queue. Only two processes can execute the operation. First, the user's valid ID is msg_perm.cuid or msg_perm.uid. Second, the superuser permission process is IPC_SET: set msg_perm.uid, msg_perm.gid, msg_perm.mode, and msg_qbytes according to the buff value. Execute the process above IPC_STAT: Put the msqid_ds Schema value in the queue to buff. ftok () function Introduction: The system establishes IPC communication (such as message queue and shared memory) Must be specified. Generally, this id value is obtained through the ftok function. The ftok prototype is as follows: when key_t ftok (char * name, int id) fname is the name of the file you specified, id is the sub-serial number. In the general UNIX implementation, the index node number of the file is taken out, and the return value of key_t is obtained by adding the sub-number before it. The method for querying the file index node number is: ls-I after deleting the reconstruction file, the index node number is allocated by the operating system according to the usage of the file system at that time, so it is different from the original one, therefore, the index node number is different. To ensure that the key_t value remains unchanged, ensure that the ftok file is not deleted or that a fixed key_t value is specified without ftok. The same program is used to ensure that two groups of identical programs under two different users obtain the IPC key values that do not interfere with each other. Because etc/config. ini (hypothesis) is the key configuration file of the application system, so there is no problem of being easily deleted-even if it is deleted, it will soon be discovered and rebuilt (and the application system will be restarted ). Ftok () is designed for this purpose. III. # include <stdlib. h> # include <string. h> # include <stdio. h> # include <errno. h> # include <sys/types. h> # include <sys/ipc. h> # include <sys/msg. h> # include <sys/stat. h> # define MSG_FILE "server. c "//!> Only the created path # define BUFFER 255 # define PERM S_IRUSR | S_IWUSR typedef struct dataType {long mID; char buffer [BUFFER + 1];} dataType; struct msgtype {long mtype; dataType mdata ;}; int main () {structmsgtype msg; key_t key; //!> Each queue has its own KEY as the int msgid; //!> If (key = ftok (MSG_FILE, 'A') =-1) //!> When fail {//!> Note that 'A' is equivalent to a flag. fprintf (stderr, "Create Key error...: % s \ n ", strerror (errno); exit (EXIT_FAILURE);} if (msgid = msgget (key, PERM | IPC_CREAT | IPC_EXCL) =-1) //!> Create msg queue {fprintf (stderr, "Create Msg error...: % s \ n ", strerror (errno); exit (EXIT_FAILURE);} printf (" \ nMsg id = % d \ n ", msgid); //!> Note that the flag here is processed as 0 while (1) //!> Receive {msgrcv (msgid, & msg, sizeof (struct msgtype), 1, 0); //!> We can know that type = 1, so we can know that the msg flag in the client is 1 //!> (Required. We can use process ID processing later.) fprintf (stderr, "Server receive: % s \ n", msg. mdata. buffer); //!> Msg. mtype = msg. mdata. mID; //!> Note that the ID must be replaced with the ID of the client process in data (otherwise the client cannot recognize it !!!!!!!) Sprintf (msg. mdata. buffer, "% d feedback received by the client! ", (Int) msg. mtype); //!> Note that the message returned by the server has changed msgsnd (msgid, & msg, sizeof (struct msgtype), 0); //!> Send back to client} exit (0) ;}# include <stdio. h> # include <stdlib. h> # include <string. h> # include <errno. h> # include <sys/types. h> # include <sys/ipc. h> # include <sys/msg. h> # include <sys/stat. h> # include <stdio. h> # define MSG_FILE "server. c "# define BUFFER 255 # define PERM S_IRUSR | S_IWUSR typedef struct dataType {long mID; char buffer [BUFFER + 1];} dataType; struct msgtype {long mtype; dataType mdata ;}; int mai N (int argc, char ** argv) {structmsgtype msg; key_t key; int msgid; if (argc! = 2) //!> You need to enter a string as the parameter {fprintf (stderr, "Usage: % s string. \ n ", argv [0]); exit (EXIT_FAILURE);} if (key = ftok (MSG_FILE, 'A') =-1) //!> Get this Key {fprintf (stderr, "Create Key error...: % s \ n ", strerror (errno); exit (EXIT_FAILURE);} if (msgid = msgget (key, PERM) =-1) //!> Obtain the queue ID {fprintf (stderr, "Create Msg error...: % s \ n ", strerror (errno); exit (EXIT_FAILURE);} msg. mtype = 1; //!> Note that the type here must match msg. mdata. mID = getpid (); //!> My ID strncpy (msg. mdata. buffer, argv [1], BUFFER); //!> Obtain the command line parameters. Only msgsnd (msgid, & msg, sizeof (struct msgtype), 0); //!> Sent to server memset (& msg, '\ 0', sizeof (struct msgtype); msgrcv (msgid, & msg, sizeof (struct msgtype), getpid (), 0 ); //!> Obtain the feedback from the server (note that the type is your own ID, so it is included in the msg sent by the server) fprintf (stderr, "Client receive: % s \ n", msg. mdata. buffer); //!> Note that only the msg of your ID is accepted !!! Exit (EXIT_SUCCESS);} 2. Run./s & //!> Server background./cILOVEYOU //!> The parameter is a string. if it is a multi-customer operation: for I in 1 2 3 4 5; do./c sss & done //!> Note that sss is a parameter. 3. Note: <1>: the client sends the same message to the server! Because the server cannot identify multiple unknown clients, however, for server feedback, you can accept the client ID, that is, the client's acceptance, according to your own process ID (in the network environment, you can accept the request based on Socket) <2>: For msg queue, a data structure such as struct msgtype {long mtype; dataType mdata; //!> Note that not only char * can be defined by yourself.}; //!> However, the overall format is required. The long sign is required !!! Typedef struct dataType {long mID; char buffer [BUFFER + 1];} dataType; note: In cs mode, server and client must enable the same queue, therefore, the same operation is required: if (key = ftok (MSG_FILE, 'A') =-1) //!> Get the same Key... get the same KEY, the msgget operation (that is, open the file, just do it yourself...) is taken from the column in shanshanpt

Related Article

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.