System v three kinds of IPC programming skillfully learn to remember __ programming

Source: Internet
Author: User
Tags data structures message queue semaphore

Reprint please keep the original address http://blog.csdn.net/guodongxiaren/article/details/43876207 Overview

Three IPC mechanisms (Message Queuing, semaphores, and shared memory) have been invented on System V ("system Five") systems, often referred to as System V IPC. It was also called XSi IPC because it was later included in the XSI standard of UNIX. So when you see system V IPC and XSI IPC, it actually means the same thing.

C language is a process-oriented language, unlike OO (object-oriented) language, it does not encapsulate data and operations. So when you're writing a C language program, you're exposed to a whole bunch of functions. The lack of OO abstraction increases the complexity of the memory, so if you don't know what to do with the function, it often makes you burn your head in programming.

This article does not detail the parameters, return values, and so on for each function, which you should find in a UNIX or Linux programming book. The purpose of this article is to help you to get through the three kinds of IPC relationship between the two channels, so as to enhance understanding, reduce memory difficulty.


Simplifying to simplify and understanding English

There is no doubt that all the identifiers in the C language are made up of English letters. If we can be good at finding all kinds of abbreviated prototypes, to understand its English interpretation, it can help us to remember.

For example, three IPC abbreviations:

abbreviation Write All Interpretation
Msg Message (queue) Message Queuing
Sem Semaphore Signal Volume
Shm Shared memory Shared memory
These three abbreviations are commonly used in the operation function of the The name of the functionAmong In addition, it appears in the corresponding header File's name. Next I will explain more about the English meaning of the function name.


Lead header files when using the three IPC mechanisms, we must call them through the system, and the headers needed for these functions need to be understood first. The header files to use for the IPC operation of System v are:

#include <sys/types.h>//Public header file, declaring the key_t type
#include <sys/ipc.h>   //Public header file

#include <sys/ Msg.h>   //Message Queue function header file
#include <sys/sem.h>//   semaphore function header file
#include <sys/shm.h>   // Header file for shared memory functions
The header files used here are all in the SYS directoryUnder the. The first two are public headers, that is, three of the IPC mechanisms are useful, and the latter three are related to specific IPC mechanisms, and we can see that they also meet the previous abbreviations by the name of the header file.
The same as the same origin Ftok ()Three IPC mechanisms use a large number of functions, different IPC uses different functions but one is the same--ftok () UNIX system has an important concept called: everything is a document.         The operations in many IPC mechanisms are for file descriptors (FD), but System V is different, it does not operate on FD, it operates on the ID of the IPC object, and the ID (identifier) is generated by the key (the key). Three kinds of IPC have their own functions to generate IDs, but the key they use is generated by function Ftok (), look at the function declaration:
#include <sys/types.h>
#include <sys/ipc.h>

key_t ftok (const char *pathname, int proj_id);
FtokThe English language can be understood as file to key's initials.         Converts the file to key. The parameter pathname is the file pathname (the file must exist, usually with the current path name "."PROJ_ID is called a child ID and specifies an integer of its own.         Note If two processes are to communicate through the IPC of System V, then the two parameters of their Ftok function must be the same so that the same key can be generated to produce the same ID. The return value type key_t is defined in <sys/types.h>, and is actually an integer (32-bit), which is the result of a path name and a child ID that work together. Here you use the STAT structure of the file path. (each file in the system has its corresponding stat structure). The 31~24 bit of the key is the second parameter of the Ftok function proj_id8-bit low. The 23~16 bit of the key is the file stat structure St_devThe lower 8 bits of the property. The 15~0 bit of the key is the file stat structure St_inoThe lower 16 bits of the property.
Ipc_permThis is a structural body. His meaning in English is: IPC Permission (IPC permissions)
struct Ipc_perm {
    key_t          __key; * Key */
    uid_t          uid;   /* Owner's valid User ID
    *          /gid_t gid;   /* Owner's valid group ID
    *          /uid_t cuid;  /* Creator's valid user ID
    *          /gid_t cgid;  /* Creator's valid group ID *
    /unsigned short mode;  /* Permission
    /unsigned short __SEQ/* can be ignored * *
;
All three kinds of IPC mechanisms have corresponding structures, which have a a common memberThis is the ipc_perm that identifies the permissions for the IPC object.
function calls are similar to

Many functions in different IPC mechanisms have the same similarities, learn to classify, find the same points and different points.

Classification Create a function control function Independent Functions
Message Queuing Msgget Msgctl Msgsnd,msgrcv
Signal Volume Semget Semctl Semop
Shared memory Shmget Shmctl Shmat,shmdt
Look sideways. You can clearly see that the same line of function names have the same head. This head is the abbreviation for the IPC mechanism: MSG, SEM, and SHM. Look at it vertically. I divide each IPC function into three categories: creating functions, control functions, and independent functions. The creation function and the control function are all three kinds of IPC, whereas the Independent function refers to the function related to the specific IPC mechanism characteristics. The creation function (get function) creates the identifier (ID) of the IPC object, which is generated with the Ftok key (key) as the parameter (and other parameters). The control function (CTL function) controls the corresponding IPC Data Structuremember properties, thereby altering the state of the IPC object. Get function analogy confirmsIn fact, the key and ID uniquely identify an IPC object, but there is no direct action on the key, but it is the turn to operate the ID, because the ID, in addition to uniquely identifying the IPC object, contains additional information (such as permissions). So by the ID generated by the GET function, you can analogy File Descriptor(FD), and the Get function is functionally analogous Open Function。 The IPC ID can only be likened to the file descriptor FD, which is not, in fact, a type of FD. Do not believe you can write a program to create a message queue, and then into the dead loop, go to the/proc/process id/fd/directory to see if there is this ID value. FD is process-dependent, and after the process terminates, the FD is released, and the IPC object does not appear before the process ends, and the process ends, and it is independent.
int Msgget (key_t key, int flag);
int Semget (key_t key, int nsems, int flag);
int Shmget (key_t key, size_t size, int flag);
This function has a flag parameter (either logical or composed) that can also be used to simulate the flag parameters of the open function, although the values are different. The flag values of these three functions are the same. Ipc_creat If key does not exist, create (o_creat with the Open function) IPC_EXCL If key exists, return failure (similar to the Open function O_excl) ipc_nowait If you need to wait, return the usual use of the error directly Is ipc_creat| IPC_EXCL, creates it if no key exists, and returns a failure if it already exists (eexist). It says a analogyMemory and Learning methods. Besides, I mentioned a Confirm, referring to the command of the shell, three of the commands in Linux are related to the three IPC of System V: IPCMK IPCRM ipcs where the IPCMK command is used to create an IPC object, look at its three main options:
Options Description
-Q Create a message queue
-S Creates a semaphore, followed by a parameter indicating the quantity
-M Create shared memory, followed by a parameter indicating size

When you create a message queue, there is no parameter behind the option, and the option to create semaphores and shared memory is followed by an argument (used to indicate the number or size). The just semaphore and shared memory get functions are also one more than message queues.
ctl function Cobwebs
int msgctl (int msqid, int cmd, struct msqid_ds *buf);
int semctl (int semid, int semnum, int cmd, ...);     There are three parameters and four parameters, according to CMD different and different
int shmctl (int shmid, int cmd, struct shmid_ds *buf);
The three CTL control functions are in fact three data structures that correspond to three kinds of IPC mechanisms: Msqid_ds Semid_ds Shmid_ds They have a common suffix- Id_ds。 DS is Data Structure(data structure) meaning. Note that the corresponding struct name of the message queue is prefixed with msq rather than MSG (this abbreviation is somewhat Shong, and the first letter of the queue is taken)
There is one of these structures a common memberThat's what I mentioned earlier. Ipc_perm。 The specific structure of each member who, here is limited, do not repeat, everyone's own Baidu Google, or to MansA bit of its corresponding control function。 Everyone in the learning process will be a layer of cobwebs, see the function of the parameter is a structure, it is necessary to explore the members of the structure, see its members are also structural body, then we must continue to explore.
These three functions have a cmd parameter (control parameters), different IPC mechanisms their control parameters are not the same. However, several control parameters are public (defined in ipc.h). The following is an example of Message Queuing (also applicable to semaphores and shared memory)
Ipc_rmid Deletes a message queue. Can only be deleted by its creator or Super User (root)
Ipc_set Sets the properties of the message queue. Set this IPC object according to the value in the structure that buf points to
Ipc_stat Read the properties of the message queue. Get the MSQID_DS structure of this queue and store it in BUF
Ipc_info (Linux only) returns system-level restrictions, resulting in buf

In addition, different IPC mechanisms also support their own control parameters, do not repeat.

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.