当前位置:网站首页>Unix Environment Programming Chapter 15 15.7 Message Queuing

Unix Environment Programming Chapter 15 15.7 Message Queuing

2022-08-09 10:29:00 Mary Soda Meatloaf

A message queue is a linked list of messages, stored in the kernel, identified by a message queue identifier, or queue ID for short.

msgget is used to create a new queue or open an existing queue.

#include int msgget(key_t key,int flag);//Successfully returns the message queue ID, failure returns -1

When creating a new queue, initialize the following members of the msqid_ds structure:

  • The ipc_perm structure is initialized as described in Section 15.6.2.The mode member in this structure is set according to the corresponding permission bit in flag.
  • msg_qnum, msg_lsqid, msg_lrpid, msg_stime and msg_rtime are all set to 0.
  • msg_ctime is set to the current time.
  • msg_qbytes is set to the system limit value.

msgsnd adds a new message to the end of the queue.

msgrcv is used to get messages from the queue.

The msgctl function performs various operations on the queue.It and two other functions related to semaphores and shared storage are XSI IPC ioctl-like functions.

#include int msgctl(int msqid,int cmd,struct msqid_ds *buf);//successful return 0, error return -1
The

cmd parameter specifies the command to be executed on the queue specified by msqid.

Call msgsnd to put data in the message queue

#include int msgsnd(int msqid,const void *ptr,size_t nbytes,int flag);//Success returns 0, failure returns -1
The

ptr parameter points to a long integer containing the positive integer message type, followed by the message data.

When msgsnd returns successfully, the msqid_ds structure related to the message queue will be updated accordingly, indicating the calling process ID, the calling time and the new message in the message queue.

msgrcv fetches messages from the queue.

#include ssize_t msgrcv(int msqid,void *ptr,size_t nbytes,long type,int flag);//Successfully returns the length of the message data part, error returns -1
The

ptr parameter points to a long integer followed by a buffer where the actual message data is stored.nbytes specifies the length of the data buffer.If the length of the returned message is greater than nbytes, and the MSG_NOERROR bit is set in the flag, the message will be truncated.If this flag is not set and the message is too long, E2BIG is returned on error.

The parameter type specifies which kind of message is desired.

type==0, returns the first message in the queue.

type>0 returns the first message of type type in the queue.

type<0 returns the message whose message type value is less than or equal to the absolute value of type in the queue. If there are several such messages, the message with the smallest type value is selected.

原网站

版权声明
本文为[Mary Soda Meatloaf]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091026200610.html