(I don’t want to create another thread) How do I limit \red{\text{main memory}} to a CPP program?
I am using Ubuntu 20.04 LTS. I want to limit the memory used by CPP Programs. Currently, I am using the following command to compile and run CPP Programs.
There are polling-based “solutions” that kind of work, but are unreliable - it’s possible for an executable to gobble memory too quickly for the poll’er to spot and kill it. The way I do it is with a separate user (called luser, with his own little directly that he can read and write) and cgroups.
Create a new user whose process memory usage you want to limit (luser in my case).
Then switch to luser, and try an executable that you know will gobble up more than the allotted limit (~1.5GB, in this case). I’m sure I had an example of this, but can’t find it now
Edit:
Here’s a dummy example:
[luser@simon-laptop][14:36:07]
[/home/simon/devel/hackerrank/otherpeoples/luser]>cat rapid-memory-gobble.cpp
#include <iostream>
using namespace std;
int main()
{
while (true)
{
new int[10'000];
}
}
[luser@simon-laptop][14:36:09]
[/home/simon/devel/hackerrank/otherpeoples/luser]>time -p ./a.out
Killed
real 2.21
user 0.28
sys 1.14
Edit2:
Aha - here’s a “real-life” example, taken from here:
[luser@simon-laptop][14:47:04]
[/home/simon/devel/hackerrank/otherpeoples/luser]>../codechef-download-solution.rb https://www.codechef.com/viewsolution/49455011
Solution written to: ghanch_2021-MUFFINS3.cpp
[luser@simon-laptop][14:47:06]
[/home/simon/devel/hackerrank/otherpeoples/luser]>../compile-latest-cpp.sh
Compiling ghanch_2021-MUFFINS3.cpp
Executing command:
g++ -std=c++17 ghanch_2021-MUFFINS3.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG -fsanitize=undefined -ftrapv
Successful
[luser@simon-laptop][14:47:11]
[/home/simon/devel/hackerrank/otherpeoples/luser]>ruby -e 'print "1000\n"; 1000.times { print "100000000\n" }' | time -p ./a.out
50000001
50000001
50000001
50000001
Command terminated by signal 9
real 7.50
user 5.33
sys 1.10