简体   繁体   中英

How to simulate “out of memory issue” in Linux

I want to reproduce one issue, pre-requisite is setting system "Out of memory" then check how a process behaves.

without affecting the other users, i have to simulate this issue, since so many other users using Linux machine in parallel.

You can set the memory available to a process by using ulimit .

Here is how you would do that in a console:

ulimit -v 64 -m 64
./program # Run the program you want to test. 

Example

Here is an example which I tested on Ubuntu 14.04. It did not work on macOS High Sierra! On Ubuntu/Linux it works fine.

// Compile with 'clang++ <filename>' or the compiler of your choice
#include <iostream>
#include <cstdlib>

int main(int argc, char** argv) {
    if (argc != 2) return 1;
    std::size_t size = std::atoi(argv[1]);
    const void* ptr = std::malloc(size);

    const std::string result = ptr ? "worked" : "failed";
    std::cout << "Allocating " << size << " bytes " << result << "." << std::endl;
}

On command line:

❯ ./a.out 100000000000000000
Allocating 1569325056 bytes worked.
❯ ulimit -v 100000 -m 100000 . # Before these values were at 'unlimited'
❯ ./a.out 100000000000000000
Allocating 1569325056 bytes failed.

If it's not too much of an overhead, you could probably run your process in a Docker container and set a memory limit. Docker would isolate your process from other parts of the system, and you can set a memory limit, too. See here about configuring a container's resources in Docker.

I think the other answer is better though, but Docker would help you minimize the impact on other users if that could be an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM