Blog.csdn.net/shanghairuo…

C and C++ Primer: C++ Primer, Effective C++, STL Source Code Parsing, Deep Search for C++ Object Models

Extern function

Extern declaration variables are defined externally? Extern modifiers? Extern C? Usage? The static keyword is used

Static modifies local variables? Static global variables? The variable is defined in a compilation unit. A compilation unit is a CPP and its included header file. Static modifies a member variable? Static modifies member functions? What does volatile do

It is more difficult to access a register than to access memory, so the CPU will preferentially access the result of the data stored in the register, but the data in memory may have changed while the original result is still in the register. To avoid this, declare the variable volatile, telling the CPU to read from memory each time. Can a parameter be const and volatile? Yes, one example is a read-only status register, volatile because it can be changed unexpectedly, and const telling the program that it should not attempt to modify it. Say as much as you can about the role of const

Const decorates a global variable; Const decorates a local variable; Const modifies pointer, const int *; Const Modifies the object to which the pointer points, int * const; Const decorates a reference as a parameter; Const modifies a member variable and must be initialized in the constructor list; Const modifies a member function, indicating that the function should not modify non-static members. But this is not very reliable. The value of a pointer to a non-member object may be changed

New allocates memory according to data type, malloc allocates memory according to size; New not only allocates a chunk of memory, but also calls the constructor, whereas malloc does not. How does new work? Int * p = new int(); int* p = new int(); int* p = new int(); After looking through the data, there is no difference between the two in C++11, and the structure of my test is also 0. New returns a pointer to the specified object, while malloc returns void*, so malloc usually needs to be cast. New is an operator that can be overloaded, malloc is a library function; The memory allocated by new is destroyed with DELETE and the memory allocated by malloc is destroyed with free. When delete is destroyed, the destructor of the object is called, while free is not; When malLOc does not allocate enough memory, realLOc can be used to expand the memory. How does capacity expansion work? New didn’t do that; New raises bad_malloc on allocation failure and returns NULL on malloc failure. So for new, the correct posture is try… Catch syntax, whereas malloc should determine the return value of the pointer. To keep up with the custom of many C programmers, C++ can also use a new nothrow method to forbid an exception and return NULL. New [] allocates all memory at once and calls the constructor multiple times, using delete and delete[], respectively. Similarly, delete[] calls the destructor multiple times, destroying each object in the array. Malloc can only sizeof(int) * n; If not, we can continue to talk about the implementation of New and malloc, free linked lists, allocation methods (first fit, best fit, worst fit, fast fit). The implementation principle of DELETE and free, why is free until how much space is destroyed? C++ polymorphism and virtual function tables

C++ polymorphic implementation? Polymorphism is classified into static polymorphism and dynamic polymorphism. Static polymorphism is implemented through overloading and templating techniques and is determined at compile time. Dynamic polymorphism is implemented through virtual functions and inheritance relationships that perform dynamic binding and are determined at run time. The realization of dynamic polymorphism has several conditions: (1) virtual function; (2) a pointer or reference to a base class points to an object of a derived class; When a base class pointer calls a member function (virtual function), it looks up the virtual function table of that object. The address of the virtual function table is at the beginning of each object. Find the pointer to the function in the virtual function table to call. Each object holds only a pointer to a virtual table. C++ internally maintains a virtual table for each class. Objects of that class point to the same virtual table. Why can we find the corresponding function pointer accurately in the virtual function table? Because the virtual function table is directly inherited from the base class when the class is designed, if one of the virtual functions is overridden, the pointer to the virtual function table is replaced, so you can find exactly which function to call based on the pointer. What does a virtual function do? Virtual functions are used to implement polymorphism, you can answer that but virtual functions are also designed to encapsulate and abstract. For example, the abstract factory pattern.

How is dynamic binding implemented? The first question is basically answered, mainly combined with the virtual function table to answer the line.

Static polymorphism and dynamic polymorphism. Static polymorphism refers to polymorphism implemented through template or function overloading techniques, which determines the behavior at the compiler. Dynamic polymorphism refers to the technique of dynamic binding at run time through virtual function technique.

Virtual function table

Is the virtual function table class-specific or object-specific? How is the virtual function table of two objects of the same class maintained? The compiler maintains a virtual table for each class. The first address of each object holds a pointer to the virtual table. Different objects of the same class actually point to the same virtual table. Pure virtual function, how to define why virtual functions for a class destructor to define virtual functions In order to achieve the polymorphism for dynamic binding, bound to the derived class object pointer to base class pointer, the object is destroyed, if the destructor is not defined for the destructor, would call the base class destructor, apparently destroy only a part of the data. If you want to call the destructor of an object, you need to define the destructor of the object as a virtual function, and find the corresponding destructor through the virtual function table during destruction.

// Virtual ~myClass() = 0; Can the 1, 2 destructor throw an exception the answer is definitely no. The C++ standard states that destructors cannot and should not throw exceptions. The greatest feature and advantage of the C++ exception handling model is that it provides the most seamless support for object orientation in C++. So if there is abnormal objects at run time, c + + exception handling model has the responsibility to remove those due to abnormal have failed, as a result of the object (i.e. objects is beyond the scope of its original), and release the object originally allocated resources, this is called the object’s destructor release resources to complete the tasks, so in this sense, Destructors have become part of exception handling.

(1) If the destructor throws an exception, the program after the exception will not be executed. If the destructor performs some necessary actions after the exception, such as releasing some resources, these actions will not be executed, resulting in problems such as resource leakage. (2) usually, when an exception occurs, the mechanism of c++ will call the destructor of the constructed object to release resources. At this time, if the destructor itself also throws an exception, the previous exception has not been handled, and there will be a new exception, which will cause the program crash.

Are virtual functions called in constructors and destructors?

The difference between Pointers and references

A pointer stores the address of the object to which it refers, and a reference is the alias of the object to which it refers. A pointer needs to be accessed indirectly by dereferencing, while a reference is accessed directly. A pointer can change the address and thus the object to which it refers, whereas a reference must be permanent; References must be initialized when they are defined, but Pointers do not; Pointers have Pointers to constants and pointer constants, while references have no constant references; Pointers are more flexible, powerful when used well, bad when used badly, while references are safer to use but more rigid. Pointers are inextricably linked to arrays

The name of a one-dimensional int array is actually an int* const; The array name of a two-dimensional int array is actually an int (*const p)[n]; An array name as an argument is reduced to a pointer, except sizeof. When do reference counts change?

The constructor initializes the count to 1; Incrementing the count in the copy constructor by 1; In the assignment operator, the object reference count on the left is reduced by one and the object reference count on the right is increased by one. Decrement the reference count in the destructor by one; In the assignment operator and destructor, if the value is zero after one decrement, delete is called to free the object. The difference between share_PRT and Weak_Ptr? Class A {public: share_ptr p; };

class B

{

public:

share_ptr<A> p;

}

int main() { while(true) { share_prt pa(new A()); // Pa reference count is initialized to 1 share_prt pb(new B()); // the reference count for pb is initialized to 1 pa->p = pb; // Pb ->p = pa; // If pa is left, the reference count is reduced by one to 1, so the destructor of class A is not called, so the member p is not destructed, and the reference count of pb is still 2; // the reference count cannot be reduced to 0 when pb leaves. }

/* ** weak_ptr is a weak reference pointer, its existence does not affect the reference count, thus solving the problem of circular reference */ C++ four types of conversion: static_cast, dynamic_cast, const_cast, reinterpret_cast

Static_cast is most commonly used to convert const variables to nonconst static_casts. For all kinds of implicit conversions, such as nonconst to const, void* to pointer, etc., static_cast can be used to convert a polymorphic variable up. Dynamic_cast is used for dynamic type conversion. Can only be used for classes that contain virtual functions, for up and down conversions between class hierarchies. Only Pointers or references can be rotated. When cast down, return NULL for pointer if it is illegal, throw exception for reference. Learn more about how internal conversion works. Reinterpret_cast almost everything can turn, such as int to pointer, may go wrong, try to use less; Why not use a cast of C? The cast of C looks powerful on the surface and can turn anything, but the conversion is not clear enough to carry out error checking, so it is prone to error. Principles of memory alignment

Storage starts at position 0; The starting position of variable storage is an integer multiple of the size of the variable; The total size of the structure is an integer multiple of its largest element. The structure contains the structure, starting from the integer multiple of the largest element in the structure; If you add pragma pack(n), take n and the smaller of the variable itself. What are the advantages of inline functions? What is the difference between inline functions and macro definitions?

Macro definitions are replaced when they are precompiled; Inline functions are replaced at the point where they are called at compile time, reducing the function call process but making the compiled file larger. Therefore, inline functions are suitable for simple functions, and complex functions may not be compiled inline even if an inline compiler is defined. Inline functions are safer than macro definitions, which check arguments, whereas macro definitions are simple text replacements. Therefore, it is recommended to use inline functions rather than macro definitions. #define MUL(a, b) ((a) * (b)) C++ memory management

What are the blocks of C++ memory? (heap, stack, constant, static, and global) what variables do blocks store? Learn to migrate, you can say malloc, from Malloc to operating system memory management, talking about kernel and user state, and then you can move on to high memory, slab layer, buddy algorithm, VMA, and then you can move on to fork(). STL memory allocation is divided into first-level allocator, which uses MALLOc to allocate memory, and second-level allocator, which uses memory pools.

The secondary dispensers are cleverly designed to give 8K, 16K… Smaller memory chips, such as 128K, maintain a free linked list, and the head node of each linked list is maintained by an array. When you need to allocate memory, take a piece from the list of appropriate size. Suppose you need to allocate a 10K block of memory, find the smallest block greater than or equal to 10K, which is 16K, and take one of the free 16K lists for allocation. When the block of memory is freed, the memory node is returned to the linked list. If the memory to be allocated is greater than 128K, the first-level allocator is called directly. To save on the cost of maintaining a linked list, a union structure is used. The allocator uses the next pointer in the union to point to the next node, and the user uses the null pointer to the union to indicate the address of the node.

What are the implementations of set and map in STL based on? What are the characteristics of red-black trees?

Both sets and maps are implemented based on red-black trees. Red black tree is a balanced binary search tree. What is the difference between it and AVL tree? AVL trees are perfectly balanced, and red-black trees are basically balanced. Why red and black numbers? Because red-black is a balanced binary tree, its efficiency of both insertion and deletion is N(logN). Compared with AVL, red-black insertion and deletion only need 3 rotations at most, while AVL trees need too many rotations in bad cases to maintain their perfect balance. The definition of red-black tree: (1) the node is red or black; (2) If the parent node is red, the child node cannot be red; (3) The number of black nodes on the path from the root node to each page child node is the same; (4) The root is black, and the NULL node is considered black. STL in other data structures and algorithm implementation should also be clear about this problem, the STL source code analysis take a good look, not only the interview is not panic, their use of STL will rise to a level.

What are the data members that must be initialized in the constructor initializer (1) constant members, which must be in the initializer list because constants can only be initialized but cannot be assigned (2) reference types, which must be initialized when they are defined and cannot be reassigned. (3) There is no default constructor for the class type, because using the initializer you can use the copy constructor instead of the default constructor to initialize the class

Template specialization (1) Template specialization is divided into full specialization and partial specialization. The purpose of template specialization is to have different implementations of a variable type, so specialized versions are required. For example, in the STL iterators specialize native Pointers to accommodate native Pointers.

Locating memory leaks (1) On the Windows platform, the CRT library functions are used to detect memory leaks. (2) Generate block snapshots before and after the invocation that may leak, compare the status before and after, and locate the leak. (3) In Linux, use the tool ValGrind to detect the leak

Handwritten strcpy

char* strcpy(char* dst, const char* src) { assert(dst); assert(src); char* ret = dst; while((*dst++ = *src++) ! = ‘\ 0’); return ret; } // This function does not take into account overlap

char* strcpy(char* dst, const char* src) { assert((dst ! = NULL) && (src ! = NULL)); char* ret = dst; int size = strlen(src) + 1; if(dst > src || dst < src + len) { dst = dst + size – 1; src = src + size – 1; while(size–) { *dst– = *src–; } } else { while(size–) { *dst++ = *src++; } } return ret; } handwritten memcpy function void * memcpy (void * DST, const void * SRC, size_t size) {if (DST = = NULL | | SRC = = NULL) {return NULL; } void* res = dst; char* pdst = (char*)dst; char* psrc = (char*)src;

If (PDST > PSRC && PDST < PSRC + size) // overlap {PDST = PDST + sie-1; psrc = pdst + size – 1; while(size–) { *pdst– = *psrc–; No overlapping {}} else / / while (size -) {* dst++ = * src++; } } return ret; } char* strcat(char* DST, const char* SRC) {char* ret = DST;

while(*dst ! = ‘\0’) ++dst;

while((*dst++ = *src) ! = ‘\ 0’); return ret; } int STRCMP (const char* str1, const char* str2) {

while(*str1 == *str2 && *str1 ! = ‘\0’) { ++str1; ++str2; } return *str1 – *str2; } The scope of investigation on data structure and algorithm is too wide, mainly relying on multiple brush questions, such as Niuke.com, OFFER, LeetCode, etc.

Hash table What are common Hash policies for implementing Hash tables (zippers and dispersed addresses)? What happens to hash_map expansion in STL? (1) Create a new bucket, which is the nearest prime number twice the size of the original bucket (the method to determine whether n is prime: divide n by 2 to SQRT (n) SQRT (n); (2) Insert the number in the old bucket into the new bucket through pointer conversion (note that STL here is very detailed, not directly copy data from the old bucket into the new bucket, but through pointer conversion) (3) swap the new bucket with the old bucket, destroy the new bucket. Tree binary tree structure, binary search tree implementation; Six kinds of traversal of binary tree; Binary tree traversal by layer; Recursion is a divine method to solve binary tree related problems. Tree algorithm of various common topic (blog.csdn.net/xiajun07061…

What is a red-black tree?

Nodes are red or black; The root node is black; The sum of the number of black nodes passing from the root node to each leaf node is the same; If the parent node is red, its children cannot be red. The difference between red-black tree and AVL tree

Both red-black trees and AVL trees are balanced trees, but AVL is completely balanced (equilibrium means that the height difference between the left and right subtrees of any node in the value tree is no more than 1). Red-black trees are more efficient because AVL inserts and deletes do logN rotations in the worst case to ensure perfect balance, whereas red-black trees insert and delete fewer rotations than AVL. Trie tree (dictionary tree)

Each node saves a character root node does not save a character Each node has at most n child nodes (n is the number of all possible characters) The complex parent of the query is O(k), k is the query string length linked list linked list and insert and delete, Consider multiple Pointers and recursion (1) printing the list in reverse (recursion) (2) printing the KTH node (front and back Pointers) (3) whether the list has a ring (fast or slow Pointers) and so on. B GGG stack and queue What is the difference between queue and stack? Characteristics (from the implementation, application, several aspects to elaborate, saying more than just a first-in, first-out, out after the first, the you will someone else will, to show you more than others to master) typical application scenario for the huge amounts of data problem billion integer (randomly generated, repeatable) first K the largest number of similar solutions ideas: First hash the data into N files, then build K element min/heap (to be chosen on request) for each file. Finally, the remaining number in the file is inserted into the heap and the heap of K elements is maintained. Finally, the elements in N heaps are combined for analysis. You can merge. In order to improve the efficiency of merging, we also need to build a maximum heap of N elements, first fill the heap with the maximum value of N, and then pop up the maximum value, move the pointer back operation. Of course, in the current Internet technology, map-Reduce framework is generally used to solve this problem. Big data sort the same idea: first hash (hash is the advantage is evenly distributed, the same number in the same file), and then small files into memory fast sorting, sorting results output to the file. Finally, merge the heap.

The 1000 most frequent integers in a billion (randomly generated, repeatable)

Sorting algorithm sorting algorithm is the basic content of course, must be at least can write quickly, fast, constructs the heap, and merge each time space complexity of the algorithm and the best of the worst average bit operations bloom filter billions of number often want to find a number is in inside, use bloom filter, the principle of bloom filter. Bloom filter may misjudge, how to ensure no error?

Networking and TCP/IP Reference books: Illustrated TCP/IP, DETAILED TCP/IP Volume 1, Illustrated HTTP, the Definitive GUIDE to HTTP

Differences between TCP and UDP (1) IP header, TCP header, and UDP header (2) Differences between TCP and UDP (3) Application scenarios of TCP and UDP (4) How to implement reliable UDP

TCP three-way handshake and four-way wave

(1) The status changes of the three-way handshake and the four-way wave. (2) What state is 2MSL? What does it do? (3) Three handshakes why not two or four?

TCP related technologies

TCP retransmission mechanism, Nagle algorithm, TCP congestion control algorithm and specific process TCP window sliding TCP client and server model, which functions are used

UDP client and server model, which functions to use

Domain name resolution process, ARP mechanism, RARP implementation

RARP is used for a diskless server. After the server is powered on, the system sends an RARP packet to the RARP server to obtain an IP address based on the MAC address

(1) Ping is implemented by sending ICMP echo request packets. (2) By sending UDP packets, TraceRoute sets the destination port to an impossible value, and sets the TTL in the IP header from 1 to N, and increases each time. If the port is unreachable, the destination host is reached. If the TTL hop count exceeds, the router sends an ICMP packet indicating that the host is unreachable. 1 2 HTTP HTTP/HTTPS 1.0, 1.1, and 2.0 HTTP has the following features: Simple and fast: When the client sends a request to the server, simply fill in the request path and request method, and then send the request through the browser or other ways. Flexible: THE HTTP protocol allows the client and the server to transmit data objects of any type and format. Connectionless means to limit processing to one request per connection. The server disconnects from the customer after processing the request and receiving the reply from the customer. In this way, the transmission time is saved. Stateless: Stateless means that the protocol has no memory for transaction processing, and the server does not know the status of the client. That is, after the client sends the HTTP request, the server will send us the data according to the request, and after sending the data, no information will be recorded. (Use cookie mechanism to maintain session and solve stateless problem)

Http1.1 features a, the default persistent connection to save traffic, as long as the client server any end is not explicitly proposed to disconnect THE TCP connection, has been connected, can send multiple HTTP requests B, pipeline, the client can simultaneously send multiple HTTP requests, and not one waiting for a response C, breakpoint continuation

HTTP/2 is fully multiplexed, not ordered and blocking — multiple requests can be responded to with a single HTTP connection. C. Use header compression. HTTP/2 reduces overhead d. HTTP/2 allows the server to proactively “push” responses into the client cache

Get/POST Difference 1: GET obtains resources from the server, and POST sends data to the server. Get transmits data through the URL request, in the form of field = value, after the URL, and with “?”. Connection, with “&” connections between multiple requests data, such as http://127.0.0.1/Test/login.action? Name =admin&password=admin, this procedure user is visible; Post Transmits data through THE POST mechanism of Http. The fields and corresponding values are stored in the request entity and sent to the server. This process is invisible to users. Difference 3: The amount of data transmitted by Get is small, because it is limited by URL length, but it is efficient; Post transfers a large amount of data. Therefore, you can upload files only in Post mode. Get is insecure because urls are visible and may reveal private information, such as passwords. Post is more secure than GET. Return status code 200: The request is processed normally 204: the request is processed but no resource can be returned 206: The client is only a part of the requested resource. The server performs the GET method on only a part of the requested resource. The corresponding packet contains the resources in the Range specified by the Content-range. 301: Permanent redirection 302: temporary redirection 303: Has a similar function to the 302 status code except that it expects clients to use the GET method when requesting a URI to be redirected to another URI. Temporary redirection, similar to 302, but the POST method is mandatory 400: The server cannot identify the request packet because the syntax is incorrect 401: The request requires authentication 403: the requested resource is forbidden 404: the server cannot find the corresponding resource 500: The server has an internal error 503: The server is busy. HTTP header data consists of four parts: the request line, the header field, the blank line, and the packet body. The header field includes the general header field, the request header field, the response header field, and the entity header field

The difference between HTTPS and HTTP? How to implement encrypted transmission? HTTPS is basically an SSL symmetric and asymmetric encryption between HTTP and the transport layer what happens when you type a URL into the browser, what protocols are used? If you enter a URL in the browser, the browser first resolves the URL to an IP address and uses the DNS protocol to resolve the domain name. The host queries the DNS cache and sends a query request to the local DNS. DNS query is divided into two methods, one is recursive query, the other is iterative query. For iterative query, the local DNS server sends a query request to the root DNS server. The root DNS server informs the level-1 DNS server of the domain name. The local DNS server then sends a query request to the level-1 DNS server, and so on until the IP address of the domain name is queried. The DNS server is udP-based and therefore uses UDP.

After getting the IP address, the browser establishes an HTTP connection with the server. Therefore, HTTP is used. The FORMAT of HTTP packets has been mentioned above. HTTP generates a GET request packet and forwards the packet to THE TCP layer for processing. If HTTPS is used, HTTP data is encrypted first. If necessary, HTTP packets are fragmented at the TCP layer according to the PATH MTU and MSS. TCP packets are then sent to the IP layer, using the IP protocol. The IP layer sends the packets to the destination address one hop at a time through route selection. Of course, addressing within a network segment is achieved by Ethernet protocol (but also other physical layer protocols, such as PPP, SLIP), Ethernet protocol requires up to the destination IP address of the physical address, there is a need for ARP protocol.

Security related Understand the attack principles and basic defense methods. The common attack methods are as follows

SQL Injection XSS CSRF SYN Flood Attack APR Spoofing database Main reference books: Database System Concepts, High Performance MySQL

SQL language (inner and outer join, subquery, grouping, clustering, nesting, logic) MySQL index method? Index optimization? How is InnoDB different from MyISAM? Four isolation levels of transactions Query optimization (optimized by index, optimized by SQL language) B- vs. B+ tree difference? What is a federated index for MySQL? Effective conditions? Linux main reference books: Modern Operating System, APUE, UNP, Linux Kernel Design and Implementation, In-depth Understanding of the Linux Kernel

(1) What is the difference between a process and a thread? (2) What are the advantages of threads over processes? (3) When to use multi-process? When to use multithreading? (4) How many functions do processes and threads use in LINUX? (5) Thread synchronization? In Linux, threads are synchronized in the following ways: mutex, spin lock, read/write lock, barrier (barrier is especially useful for concurrent completion of the same task) know the difference between these locks. Use scenario?

Interprocess communication (PIPE) : A pipe is a half-duplex communication mode in which data flows only in one direction and can only be used between related processes. Process kinship usually refers to the parent-child process relationship.

Named Pipes (FIFO) : Named pipes are also a half-duplex communication mode, but allow communication between unrelated processes.

Semaphores: Semaphores are used to implement mutual exclusion and synchronization between processes, rather than to store inter-process communication data. There are XSI semaphores and POSIX semaphores, which are more sophisticated.

Message queue: MESSAGE queues are linked lists of messages stored in the kernel and identified by message queue identifiers. The message queue overcomes the disadvantages of little signal transmission, pipe carrying only plain byte stream and limited buffer size.

Shared memory: A shared memory map maps a segment of memory that can be accessed by other processes. This shared memory is created by one process but can be accessed by multiple processes. Shared memory is the fastest IPC method and is specifically designed for the low efficiency of other interprocess communication methods. It is often used in conjunction with other communication mechanisms, such as signal two, to achieve synchronization and communication between processes. (The principle must be clear, often test)

Sinal: A complex form of communication used to inform the receiving process that an event has occurred.

Socket: A socket is also an interprocess communication mechanism. Unlike other communication mechanisms, it can be used to communicate between different processes.

Anonymous pipes differ from named pipes: Anonymous pipes can only be used between two processes that have a common ancestor. Shared File mapping Mmap Mmap establishes the mapping between the process space and files. During the mapping, files are not directly copied to the physical memory, and the page missing terminal is also used. Mmap maps a specific file to realize shared memory between any processes, and maps an anonymous file to realize shared memory between parent and child processes.

What are the common signs? : SIGINT, SIGKILL(can’t be caught), SIGTERM(can be caught), SIGSEGV, SIGCHLD, SIGALRM

Memory management What does virtual memory do? Virtual memory implementation? Memory management at the OS level? What does a memory pool do? How to implement the memory pool in STL? Process space and kernel space manage memory differently? Slab layer of Linux, VAM? Linux processes are divided into two types, real-time process and non-real-time process. Priority is classified into static priority and dynamic priority, and priority ranges. Scheduling strategy, FIFO, LRU, time slice rotation interactive processes are rewarded by average sleep time; Deadlock (1) conditions for deadlock generation; (2) Deadlock avoidance;

Command line Linux commands in a file, Reverse order to print the second 100 capital letters before cat filename | head – n 2 | tail – n 1 | grep ‘[[: upper:]]’ – o | tr -d ‘\ n’ | cut 1-100 – c | rev 1 to the CPU, Memory, disk-related commands (top, free, df, fdisk)

Netstat and tcpdump commands

Sed, awk, grep three super powerful naming, respectively used with formatting modification, statistics, and re lookup

Ipcs and ipCRM commands

Find the current directory and the path to files ending in. C and containing “Hello World”

Creating a Scheduled Task

IO model There are five IO models: blocking IO, non-blocking IO, I/O multiplexing, signal-driven IO, and asynchronous IO

Select, poll, epoll

Select is the original solution to THE I/O blocking problem. The structure fd_set tells the kernel to listen for multiple file descriptors. This structure is called a descriptor set. The array maintains which descriptors are set. Operations on structures are encapsulated in three macro definitions. Find if there is a descriptor to be processed by round search, if there is no problem with ** : 1. The built-in array makes the maximum number of files in select limited by FD_SIZE; 2. Reinitialize the descriptor set before each call to select, copy the fd from the user state to the kernel state, and copy the FD from the kernel state to the user state after each call to select. 3. Round search when there are a large number of file descriptors, the efficiency is low.

Poll: Resolves the select file descriptor constraint problem with a variable length array. The elements of the array are structures that hold descriptor information. Each additional file descriptor adds a structure to the array. The structure only needs to be copied to the kernel state once. Poll solves the problem of repeated initialization of select. The canvass problem has not been solved. 六四屠杀

Epoll: The efficiency of polling all file descriptors is not high, which limits the concurrent capability of the server. Therefore, epoll solves the round-seeking bottleneck by returning only file descriptors with state changes. – Why use IO multiplexing, what is the main reason? – Epoll has two trigger modes? What is the difference between the two trigger modes? What’s the difference when programming? – on a topic in the program have what distinction, is in the edge of the trigger to read data from the socket when clean, so when there are multiple socket, reading the socket has been constantly arrive data, how to ensure that other socket is not starve to death (netease game the interview when asked a question, and answer, thief impressive).

Select /poll/epoll thread pool select/poll/epoll thread pool Fork and vfork are both used to create child processes. But after vfork creates the child, the parent blocks until the child calls exit() or excle(). The kernel calls the clone function for fork, which then calls do_fork(). The do_fork() function calls copy_process() to copy the task_struct structure and then other information about memory, files, registers, etc. Fork uses copy-on-write technology, so the child and parent’s page tables point to the same page box. However, vfork does not need to copy the page table because the parent process blocks all the time and uses the parent page table directly.

The difference between exit() and _exit() is that exit() is cleaned and goes into the kernel, while _exit() goes directly into the kernel.

Orphan and zombie processes

How did the orphan process come about? How do zombie processes occur? The perils of zombie processes? How do you avoid zombie processes? How does Linux avoid memory fragmentation

Partner algorithm, used to manage physical memory, avoid memory fragmentation; The cache Slab layer is used to manage kernel allocated memory and avoid fragmentation. How does shared memory work? Shared memory implementation is divided into two ways: one is to use MMAP, the other is to use XSI mechanism of shared memory method. Mmap is a memory file mapping that maps a file to the address space of a process. The address space of a user process is managed through the VM_areA_struct structure. Mmap can map the same file to two different processes and realize the communication between the two processes. This method can realize the communication between any process. Mmap can also use anonymous mapping without specifying mapped files, but can only communicate between parent and child processes. XSI memory sharing is actually implemented by mapping files, but it maps files in a special file system that are not accessible by read and write.

Differences between the two:

1. The data in system V shared memory is never written to the actual disk file; Shared memory communication via mmap() mapping normal files can specify when data is written to disk files. Note: As mentioned earlier, the system V shared memory mechanism is actually implemented by mapping files in the special file system SHM, which is installed on the swap partition. After the system reboots, all contents are lost.

2. System V shared memory is persistent with the kernel. Even if all processes accessing the shared memory have terminated normally, the shared memory area still exists (unless explicitly deleted), and any overwrites to the shared memory area are retained until the kernel reboots.

3. When communicating between processes by calling mmap() to map common files, it is important to consider the impact of process termination on communication. Processes that communicate through system V shared memory do not. Note: The SHMCTL usage example is not given here, the principle is similar to message queue.

System calls and library functions (open, close, Create, lseek, write, read)

What are the synchronization methods?

Mutex, spin lock, semaphore, read/write lock, barrier The difference between a mutex and a spin lock is that the mutex blocks when resources are unavailable and does not consume CPU resources. When the spin lock does not have resources, it continuously queries, but consumes CPU resources. Deadlock other ++ I is atomic operation obviously not, ++ I has three main steps, put data from the register, increment in the register, copy data from the register into memory, each step may be interrupted.

Judge size end

union un

{

int i;

char ch;

};

void fun() { union un test; test.i = 1; If (ch == 1) cout << endl; Else cout << “big end” << endl; } Design pattern singleton pattern thread-safe writing STL iterator uses the iterator pattern MVC understanding distributed system Map_Reduce principle (this article is very easy to understand) load balancing CDN part of the problem is just to list the outline of thinking, To find the answers to these questions in books and in practice can be truly digested.

PS: Welcome to reprint, reprint please indicate the source! — — — — — — — — — — — — — — — — — — — — – the author: oscarwin source: CSDN, blog.csdn.net/shanghairuo… Copyright notice: This article is the blogger’s original article, reprint please attach the blog link!