Joshua Tyler
Joshua Tyler

Reputation: 35

Memory limit pre process using pid in centos 7

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

Answers (1)

Alex V
Alex V

Reputation: 3644

Memory limits for processes in Linux usually go like this:

  1. You set a memory limit for your current process via the setrlimit system call (man page)
  2. Run the process who's memory you want to limit. The child will inherit the parent's limit upon creation.
  3. Viola! You are now running the child process with the memory limit set to your liking.
  4. Reset the parent's memory limit (which won't effect the child!)

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

Related Questions