[英]How to simulate “out of memory issue” in Linux
我想重现一个问题,先决条件是将系统设置为“内存不足”,然后检查进程的行为。
在不影响其他用户的情况下,我必须模拟此问题,因为许多其他用户并行使用Linux计算机。
您可以使用ulimit设置进程可用的内存。
这是在控制台中执行的操作:
ulimit -v 64 -m 64
./program # Run the program you want to test.
这是我在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;
}
在命令行上:
❯ ./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.
如果没有太大的开销,则可以在Docker容器中运行进程并设置内存限制。 Docker会将您的进程与系统的其他部分隔离开来,您也可以设置内存限制。 有关在Docker中配置容器资源的信息,请参见此处 。
我认为其他答案更好,但是Docker可以帮助您最大程度地减少对其他用户的影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.