Linux memory usage

Source: Internet
Author: User
Redhat-config-network-tui is a unique configuration tool for redhat. when you use this command to configure network parameters, it will be written to the/etc/sysconfig/networking/profiles/directory, and better than network-scripts/ifcfg-eth0

I am a programmer, so here I will explain how to use Linux memory from a programmer's perspective.

When talking about memory management, the two concepts that pop up in our minds are virtual memory and physical memory. These two concepts are mainly supported by the Linux kernel.

Linux has two levels of memory management. The first level is a linear zone, which is similar to 00c73000-00c88000. it corresponds to the virtual memory and does not actually occupy the actual physical memory. The first level is a specific physical page, it corresponds to the physical memory on our machine.

A very important concept is mentioned here: memory delay allocation. When a user applies for memory, the Linux kernel only allocates a linear zone (that is, virtual memory) to the user and does not allocate the actual physical memory. only when the user uses the memory, the kernel allocates a specific physical page to the user, which occupies valuable physical memory. The kernel releases the physical page by releasing the linear zone, finding the corresponding physical page, and releasing it all.

Char * p = malloc (2048) // only 2048 of the virtual memory is allocated and does not occupy the actual memory.

Strcpy (p, "123") // allocates a physical page. although only three bytes are used, the memory still allocates 2048 bytes of physical memory for it.

Free (p) // find the corresponding physical page through the virtual address, release the physical page, and release the linear area.

We know that the user's process and kernel run at different levels, and the communication between the process and the kernel is completed through system calls. Processes are applying for and releasing memory, mainly through brk, sbrk, mmap, and unmmap system calls. the passed parameters are mainly the corresponding virtual memory.

Note that a process can only access virtual memory, but does not actually see the use of the kernel physical memory, which is completely transparent to the process.

Glibc memory manager

So every time we call malloc to allocate a piece of memory, what about system calls?

The answer is No. here I want to introduce a new concept, memory manager of glibc.

We know that functions such as malloc and free are included in the library functions in the glibc Library. let's think about how inefficient the program will be if every memory operation calls a system call.

In fact, glibc uses a wholesale and retail method to manage memory. Glibc requests a large block of memory (virtual memory) each time it calls the system. when the process requests the memory, glibc extracts a block from its own memory to the process.

Difficulties faced by the memory manager

When we write a program, the size of the memory block requested each time is irregular, and frequent application and release exist. This will inevitably lead to memory fragmentation. However, memory fragmentation directly results in a failure to meet the application of large memory blocks, thus occupying more system resources. if the chunks are organized, the cpu load will increase, many of them are conflicting indicators. I will not elaborate on them here.

When writing a program and involving memory, we have two concepts: heap and stack. Traditionally, the memory address of the stack increases downward, and the heap memory address increases upwards.

The malloc and free functions are mainly used for heap operations, and the programmer controls the access to memory.

Here, the heap memory address increases upwards. This sentence is not completely correct.

Glibc uses mmap to apply for memory larger than kB for heap memory applications. This does not ensure that the memory address increases upwards. brk is used for memory applications smaller than KB, it is correct. The threshold value of KB can be set through the library function of glibc.

Here I will first talk about the application of large memory, that is, corresponding to the mmap system call.

For large memory applications, glibc uses the mmap system call to divide it into another virtual address for separate use by the process. when the memory is released, use the unmmap system call to release the memory. this process will not cause issues such as memory fragmentation.

For small memory applications, after the program starts, the process will get an address at the bottom of the heap. every time the process applies for memory, glibc will increase the heap to expand the memory space, that is to say, the heap address increases upwards. When performing operations on these small blocks of memory, the memory fragmentation problem occurs. In fact, the brk and sbrk system calls are to adjust the heap top address pointer.

When will the heap memory be released?

When glibc finds that the heap top has consecutive free space, it will adjust the heap top position through brk or sbrk system calls and return the occupied memory to the system. In this case, the kernel will release the occupied physical memory by deleting the corresponding linear zone.

The following is a question about memory holes:

In one scenario, there is a memory in use at the top of the heap, and a large continuous memory has been released below. can this memory be released? Can the corresponding physical memory be released?

Sorry, no.

That is to say, as long as the applied memory at the top of the heap is still in use, I will release more memory below and will not be returned to the system, but still occupy the physical memory. Why?

This is mainly because the kernel is too simple to process the heap. it can only adjust the linear zone occupied by the program by adjusting the heap top pointer; however, you can only release the memory by adjusting the linear zone. So as long as the heap top is not reduced, the occupied memory will not be released.

Ask a question:

Char * p = malloc (2 );

Free (p)

Why do I need two parameters when applying for memory? one is the memory size and the other is the returned pointer. but when the memory is released, what is the memory pointer?

This is mainly related to the memory management mechanism of glibc. In glibc, a chunk structure is maintained for each piece of memory. When glibc allocates memory, glibc first fills in the size of the memory block in the chunk structure, and then allocates the memory to the process.

Chunk ------ size

P ------------ content

When a process releases the memory, the memory size of the block can be found as long as the pointer-4 is used to release the memory.

Note: glibc allocates at least 16 bytes for memory application to maintain the chunk structure.

Debugging tools provided by glibc:

To facilitate debugging, glibc provides users with hooks for functions such as malloc, such as _ malloc_hook.

Corresponds to a function pointer,

Void * function (size_t size, const void * caller)

Among them, caller is the receiver that calls the return value of malloc (the address of a pointer ). In addition, the _ malloc_initialize_hook function pointer is called only once (when dynamic memory is allocated for the first time ). (Malloc. h)

Some statistics using malloc (SVID extension) can be stored using struct mallinfo,

Available.

Struct mallinfo (void)

How to detect memory leakage? Glibc provides a function

Void mtrace (void) and void muntrace (void)

At this time, it depends on a file referred to by the environment variable MALLOC_TRACE and records some information in this file.

Used to detect memory leakage. in essence, the hook mentioned above is installed. These functions are generally used

# Ifdef DEBUGGING packages to reduce overhead in non-debug mode. It is said that it is not recommended to read the generated files by yourself,

Use the mtrace program (perl script for analysis ). The following is a simple example to illustrate this process.

SOURCE program:

# Include

# Include

# Include

Intmain (int argc, char * argv [])

{

Int * p, * q;

# Ifdef DEBUGGING

Mtrace ();

# Endif

P = malloc (sizeof (int ));

Q = malloc (sizeof (int ));

Printf ("p = % pnq = % pn", p, q );

* P = 1;

* Q = 2;

Free (p );

Return 0;

}

Q is not released. We set the environment variable and touch the file.

The execution result is as follows:

P = 0x98c0378q = 0x98c0388

The file content is as follows:

= Star

T @./test30: [0x8048446] + 0x98c0378 0x4

@./Test30: [0x8048455] + 0x98c0388 0x4

@./Test30: [0x804848f]-0x98c0378

At this point, I have basically finished talking about the memory usage of some data during Program writing.

Memory occupied by code

The data part occupies the memory. Does the program we write also occupy the memory?

In linux, program loading involves two tools: linker and loader. Linker mainly involves the use of dynamic link libraries, and loader mainly involves software loading.

1. execute a program in exec.

2. elf is a very popular executable file format. it divides the program running into two segments. one segment is an executable segment, which is read-only and executable; the other segment is the data segment, which can be read/written and cannot be executed.

3. the loader will start and map the code end and data segment to the memory through mmap system call. In fact, virtual memory is allocated for it. Note that physical memory is not used at this time; the kernel allocates physical memory to the program only when the program is executed.

4. loader searches for the link library that the program depends on. First, it checks whether the link Library is mapped into the memory. if mmap is not used, the code segment and data segment are mapped to the memory, otherwise, it is only added to the address space of the process. In this way, the memory address space of libraries such as glibc is exactly the same.

Therefore, the execution of a 2 m program does not mean that it is allocated with 2 m physical memory, which is related to the amount of code running and the dynamic link library on which it depends.

The difference between linking a dynamic link library during running and linking a dynamic link library during compilation.

There are two ways to call the dynamic link library: one is to specify the dynamic link library to be depended on during compilation, so that the loader can start the program, all dynamic links are mapped to the memory. one is to load the dynamic link library through dlopen and dlfree during running, and dynamically load the dynamic link library to the memory.

From the programming perspective, the first two methods are the most convenient, with little impact on efficiency and some differences in memory usage.

The first method is to run the code of a database once, which will occupy the physical memory and occupy the physical memory even if it is no longer used until the process is terminated.

Second, the memory occupied by the library code can be released in the dlfree mode and returned to the physical memory.

This difference is mainly related to processes that have a long life, but occasionally call various libraries. For such processes, we recommend that you use the second method to call the dynamic link library.

Memory usage measurement

Measure how much memory a process occupies. linux provides us with a very convenient method. The/proc directory provides us with all the information, in fact, the top tool also obtains the corresponding information here.

/Proc/meminfo memory usage information of the machine

/Proc/pid/maps pid is the process number and displays the virtual address occupied by the current process.

Memory occupied by/proc/pid/statm process

[Root @ localhost ~] # Cat/proc/self/statm

654 57 44 0 0 334 0

Output description

CPU and CPU 0... The meaning of each parameter in each row (in the first behavior example) is:

Parameter description/proc // status

Size (pages) task virtual address space Size VmSize/4

The size of the physical memory that the Resident (pages) application is using VmRSS/4

Shared (pages) Shared pages 0

Size of executable virtual memory owned by the Trs (pages) program VmExe/4

The size of the library that the Lrs (pages) is mapped to the virtual memory space of the task. VmLib/4

Drs (pages) program data segment and user-State stack size (VmData + VmStk) 4

Dt (pages) 04

View available machine memory

/Proc/28248/> free

Total used free shared buffers cached

Mem: 1023788 926400 97388 0 134668 503688

-/+ Buffers/cache: 288044 735744

Swap: 1959920 89608 1870312

When we run the free command to view the idle memory of the machine, we will find that the free value is very small. This is mainly because there is such an idea in linux, the memory does not need to be white, so it tries its best to cache and buffer some data for the next use. But in fact, these memories can also be used immediately.

So free memory = free + buffers + cached = total-used

View memory used by the process


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.