如何模拟Linux中的"内存不足问题"

Aru*_*san 1 linux

我想重现一个问题,先决条件是设置系统"Out of memory"然后检查进程的行为方式.

在不影响其他用户的情况下,我必须模拟这个问题,因为许多其他用户并行使用Linux机器.

Una*_*dra 8

您可以使用ulimit设置进程可用的内存.

以下是在控制台中执行此操作的方法:

ulimit -v 64 -m 64
./program # Run the program you want to test. 
Run Code Online (Sandbox Code Playgroud)

这是我在Ubuntu 14.04上测试的一个例子.它不适用于macOS High Sierra!在Ubuntu/Linux上它工作正常.

// 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;
}
Run Code Online (Sandbox Code Playgroud)

在命令行上:

? ./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.
Run Code Online (Sandbox Code Playgroud)