1. Message Queue
1. Implementation principle
The operating system sets up a queue in the kernel. The two processes AB of communication pushback the data to be sent into the queue in the form of data blocks. The data block is a structure, and there are fields that identify who sent the data block, so we just need to let different processes see the same queue.
2. System call interface
(I) Create and get a message queue
msgget
The main function of the function is to create a new message queue or obtain the identifier of an existing message queue.
#include <sys/> #include <sys/> #include <sys/> int msgget(key_t key, int msgflg);
Return value: Return one successfullymsgid
, failed to return -1
-
key
: The return value of the ftok function -
msgflg
: Identifier
function | msgflg | effect | Example |
---|---|---|---|
msgget | IPC_CREAT | If the message queue corresponding to the specified key does not exist, a new message queue is created; if it already exists, the identifier of the message queue is directly returned | msgget(key, IPC_CREAT | 0666) |
msgget | IPC_EXCL | Usually used with IPC_CREAT. If these two flags are set at the same time, when the message queue already exists, the msgget call will fail and return -1, and errno will be set to EEXIST | msgget(key, IPC_CREAT | IPC_EXCL | 0666) |
msgget | 0600 | The owner of the message queue has read and write permissions, and the group and other users do not have any permissions. | msgget(key, 0600) |
msgget | 0660 | The owner and group of the message queue have read and write permissions, and other users do not have permissions. | msgget(key, 0660) |
msgget | 0666 | The owner, group to which the message queue has read and write permissions | msgget(key, 0666) |
(II) Control the message queue
msgctl
System call functions used to control message queues, which are usually used to perform various management operations on message queues, such as obtaining message queue status, setting message queue attributes, and deleting message queues.
#include <sys/> #include <sys/> #include <sys/> int msgctl(int msgid, int cmd, struct msqid_ds *buf);
Return value: Returning 0 means the operation is successful, and returning -1 means the operation is failed.
-
msgid
: Message queue identifier,msgget
Function returns value -
cmd
:msgctl
Functionalcmd
Common parameters are as follows:
Order | illustrate |
---|---|
IPC_STAT | Get the status information of the message queue and store the information in the msqid_ds structure pointed to by buf. These information include permissions of the message queue, owner information, size of the message queue, current number of messages, etc. |
IPC_SET | Set the attributes of the message queue according to the value in the msqid_ds structure pointed to by buf. Attributes that can be set include permissions of the message queue, maximum number of bytes of the queue, etc. |
IPC_RMID | Delete the specified message queue. After calling this command, the message queue will be deleted immediately, all queued messages will be discarded, and resources related to the message queue will be released. |
MSG_INFO | Obtain system resource usage information related to message queues, such as the total number of message queues in the current system, the maximum number of message queues allowed by the system, etc. |
MSG_STAT | This command is similar to IPC_STAT, but it returns a pointer to the struct msg_info structure, which contains more statistics about the message queue, such as the number of bytes sent and received messages, etc. |
-
buf
: A pointermsgid_ds
A pointer to a structure, used to store or provide relevant information about a message queue,msqid_ds
The structure contains various attributes of the message queue, such as the permissions of the queue, owner information, the size of the message queue, etc.
(III) Send a message
msgsnd
System call function for sending messages to message queues, which allows the process to add a message to the specified message queue.
#include <sys/> #include <sys/> #include <sys/> int msgsnd(int msgid, const void *msgp, size_t msgsz, int msgflg);
Return value: Return 0 for success, return -1 for failure
-
msgid
: Message queue identifier,msgget
Function returns value -
msgp
: A pointer to the message structure to be sent. The first member of the structure must be of type long, which specifies the type of the message. It can subsequently contain the data part of the message -
msgsz
: The length of the message data part, i.e.msgp
Except for the first one in the pointed structurelong
Data length outside the type member -
msgflg
: This position is 0, which means it is not set
function | msgflg | effect | Example |
---|---|---|---|
msgsnd | IPC_NOWAIT | Send messages non-blocking. When the message queue is full and cannot send messages immediately, if this flag is set, the msgsnd function will immediately return -1, and errno is set to EAGAIN; if this flag is not set, the msgsnd function will block until the message queue has room to send messages. | msgsnd(msgid, &msgbuf, sizeof(), IPC_NOWAIT) |
(IV) Get data blocks in the message queue
msgrcv
System call function for receiving messages from message queues, which allows processes to get messages from specified message queues
#include <sys/> #include <sys/> #include <sys/> ssize_t msgrcv(int msgid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
Return value: successfully returns the number of bytes of the actual received message data part, excluding the first long
The first two parameters are the same as before
-
msgsz
: The maximum length of the buffer used to store the message data part when receiving a message -
msgtyp
: If it is equal to 0, then the function only receives the first message in the message queue. If it is greater than 0, the message type in the receiving message queue ismsgtyp
If the first message is less than 0, the message type in the receiving message queue is less than or equal tomsgtyp
The first message of the minimum type of absolute value -
msgflg
: This position is 0, which means it is not set
function | msgflg | effect | Example |
---|---|---|---|
msgrcv | IPC_NOWAIT | When there is no message that meets the requirements in the message queue, if this flag is set, the msgrcv function will immediately return -1, and errno is set to ENOMSG; if this flag is not set, the msgrcv function will block until a message that meets the requirements enters the message queue | msgrcv(msgid, &msgbuf, sizeof(), msgtype, IPC_NOWAIT) |
msgrcv | MSG_NOERROR | If the received message length exceeds the specified buffer size, if this flag is set, the message will be truncated to the buffer size, and the excess will be discarded, and the msgrcv function returns normally; if this flag is not set, the msgrcv function will return -1, and errno will be set to E2BIG | msgrcv(msgid, &msgbuf, sizeof(), msgtype, MSG_NOERROR) |
2. Semaphore
1. Principle
Semaphore is a type used to implement inter-processSynchronization and mutual exclusionThe mechanism of the semaphore is essentially an integer variable used to control access to shared resources. It can be regarded as a special counter, and its value represents the number of shared resources currently available. The value of the semaphore can be read and modified by multiple processes or threads. Through operations on the semaphore, the process or thread can coordinate access to shared resources.
The work of semaphores is based on two basic operations: P operation (wait operation) and V operation (signal operation)
-
P operation
: When a process or thread needs to access a shared resource, it performs a P operation. The P operation will decrement the value of the semaphore by 1. If the value of the semaphore after decrement is greater than or equal to 0, it means that there are currently available resources and the process or thread can continue to access; if the value of the semaphore after decrement is less than 0, it means that there are no available resources and the process or thread will be blocked until another process or thread releases the resources. -
V Operation
: When a process or thread uses a shared resource, it will perform a V operation. The V operation will add the value of the semaphore to 1. If the value of the semaphore after adding 1 is less than or equal to 0, it means that other processes or threads are waiting for the resource. At this time, a waiting process or thread will be awakened
2. System call interface
(I) Create and get a semaphore
semget
is a system call function used to create or obtain a semaphore set
#include <sys/> #include <sys/> #include <sys/> int semget(key_t key, int nsems, int semflg);
Return value: successfully returned semaphore identifiersemid
, failed to return -1
-
nsems
: Indicates the number of semaphores in the semaphore set to be created or obtained. If it is to create a new semaphore set, it must be greater than 0. If it is to obtain an existing semaphore set, it can be 0. -
semflg
: Flag bit, used to specify how and permissions to create or obtain semaphore sets
(II) Control the signal quantity
semctl
It is a system call function used to control the semaphore set. It can perform various operations on the semaphore set, such as initializing the value of the semaphore, obtaining the status of the semaphore, deleting the semaphore set, etc.
#include <sys/> #include <sys/> #include <sys/> int semctl(int semid, int semnum, int cmd, ...);
Return value: depends oncmd
The current value ofGETVAL
Command, returns the current value of the specified semaphore, forIPC_STAT
、IPC_SET
andIPC_RMID
Wait for the command, return 0 means success
-
semid
: semaphore identifier,semget
Function returns -
semnum
: The number of semaphores in the semaphore set, the number starts from 0. If the cmd operation does not require a specific semaphore (such as deleting the entire semaphore set), this parameter can be ignored and usually set to 0 -
cmd
: The command to be executed specifies the type of operation for the semaphore set or a specific semaphore
(III) PV operation
semop
System call function for performing operations on a semaphore set, which allows a process to perform atomic P and V operations on one or more semaphores, thereby enabling synchronization and mutual exclusion between processes.
#include <sys/> #include <sys/> #include <sys/> int semop(int semid, struct sembuf *sops, unsigned nsops);
Return value: Return 0 for success, return -1 for failure
-
sops
: Point tostruct sembuf
Pointer to a structure array containing the sequence of operations to be performed on the semaphore set -
nsops
:sops
The number of elements in the array, that is, the length of the sequence of operations to be performed
3. Comparison of systemV IPC methods
1. Describe the structure of IPC resources
Description shared memoryIPC
Resource structure:
struct shmid_kernel /* private to the kernel */ { struct kern_ipc_perm shm_perm; struct file * shm_file; int id; unsigned long shm_nattch; unsigned long shm_segsz; time_t shm_atim; time_t shm_dtim; time_t shm_ctim; pid_t shm_cprid; pid_t shm_lprid; struct user_struct *mlock_user; };
Describe message queueIPC
Resource structure:
struct msg_queue { struct kern_ipc_perm q_perm; time_t q_stime; /* last msgsnd time */ time_t q_rtime; /* last msgrcv time */ time_t q_ctime; /* last change time */ unsigned long q_cbytes; /* current number of bytes on queue */ unsigned long q_qnum; /* number of messages in queue */ unsigned long q_qbytes; /* max number of bytes on queue */ pid_t q_lspid; /* pid of last msgsnd */ pid_t q_lrpid; /* last receive pid */ struct list_head q_messages; struct list_head q_receivers; struct list_head q_senders; };
Describe the semaphoreIPC
Resource structure:
struct sem_array { struct kern_ipc_perm sem_perm; /* permissions .. see */ time_t sem_otime; /* last semop time */ time_t sem_ctime; /* last change time */ struct sem *sem_base; /* ptr to first semaphore in array */ struct sem_queue *sem_pending; /* pending operations to be processed */ struct sem_queue **sem_pending_last; /* last pending operation */ struct sem_undo *undo; /* undo requests on this array */ unsigned long sem_nsems; /* no. of semaphores in array */ };
They have the same characteristic that the first parameter isstruct kern_ipc_perm
Type of
struct kern_ipc_perm { spinlock_t lock; int deleted; key_t key; uid_t uid; gid_t gid; uid_t cuid; gid_t cgid; mode_t mode; unsigned long seq; void *security; };
2. The operating system manages IPC resources
All IPC resources have onestruct kern_ipc_perm
structure, so the operating system uses an array to transfer thesestruct kern_ipc_perm
Structured
ipc_ids
Yes for management in Linux kernelIPC
The core data structure of the resource
struct ipc_ids { int in_use;//Record the number of IPC resources being used in the current system int max_id;//Indicate the maximum IPC identifier value allowed in the system unsigned short seq;// is a serial number used to generate a unique IPC identifier unsigned short seq_max;//is the maximum value of the serial number struct semaphore sem;//This is a semaphore used to synchronously control concurrent access to IPC resources struct ipc_id_ary nullentry;// An empty ipc_id_ary structure struct ipc_id_ary* entries;// Pointer to ipc_id_ary structure};
struct ipc_id_ary { int size; struct kern_ipc_perm *p[0]; };
The flexible array herep
The function is to maintain all the current operating systemIPC
Resources, which we use cast to store in this arraystruct ipc_id_ary*
Find the specific oneIPC
object, becausekern_ipc_perm
It is the first member of these three structures, we only know onekern_ipc_perm
The address is equivalent to knowing a specificIPC
The object's start address can then be accessed through cast type conversionIPC
All member properties in the object, thus implementing a specificIPC
Access to objects, such as((struct shmid_kernel*)p[0])->q_stime
,existkern_ipc_perm
There are fields in it to identify thekern_ipc_perm
Which one belongs toIPC
The operating system knows what type to force it to convert resources, which we use at the user level:shmid
、msqid
、semid
It's in the kernelp
Subscript of array
ipc_id_arry
It belongs to the operating system, not to any process, the array subscript is linearly incremented, but it will not be becauseIPC
The resource is released and its incremental attribute is changed, that is, the last one in the current operating systemIPC
The resource's subscript is 100, release thisIPC
Resource, create next timeIPC
When the resource is in the subscript is 101, not 100. When it is incremented to a certain value, it will return to 0.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.