Reputation: 35
I'm looking to limit the memory to a process using pid in script i'm looking to see what i could use maybe something like cpulimit or some other software
Upvotes: 1
Views: 1064
Reputation: 3644
Memory limits for processes in Linux usually go like this:
setrlimit
system call (man page)In practice, that looks like this:
$ ulimit -v [memory limit kilobytes]
$ ./[program who's memory you want to limit]
$ ulimit -v unlimited
A great tool that does exactly this is Firejail. Using Firejail we can sprout a child process with a memory limit of 512 bytes like so:
firejail --rlimit-as=number [command]
However, unlike ulimit
, firejail does not come installed with CentOS by default.
I realize this is not precisely what you asked for. I'm telling you how to start a process with a memory restriction placed upon it, whereas strictly speaking you only asked how to modify the memory available to a running process via it's PID.
Unlike CPU and file access limits, memory limitation on any Linux distro is vastly simpler if performed at process creation time, rather than at runtime. This is due to the design of the kernel, specifically the setrlimit
syscall I mentioned earlier. So although it could be possible.
However, if you are absolutely determined to dynamically altering an existing process's memory limit, it can be done using cgroups. All you have to do is create a cgroup with a specific memory limit and place your process in that cgroup. You should do something like this:
mkdir /sys/fs/cgroup/memory/groupname
echo 1000 > /sys/fs/cgroup/memory/groupname/memory.limit_in_bytes
echo pid > /sys/fs/cgroup/memory/groupname/cgroup.procs
That approach is closer to what you asked for, however the first approach is much simpler and I highly recommend it if it's at all feasible for your problem. Good luck!
Upvotes: 4