簡體   English   中英

如何在Linux中模擬“內存不足問題”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM