Directly set by echo 1000 >/proc/<pid>/oom_score_adj is unreliable because target program is already running , in this case maybe target program caused OOM before echo 1000 >/proc/<pid>/oom_score_adj
2 Answers
oom_score_adj is inherited on fork, so you can set its initial value for new children by setting the desired value on the parent process.
Thus if you’re starting the target from a shell script,
echo 1000 > /proc/$$/oom_score_adj will change the shell’s value to 1000, and any process subsequently forked by the shell will start with oom_score_adj set to 1000.
As an alternative to setting it on the parent process, as in M. Kitt's answer, one can set it on the child process after the fork by running the program in the child process via a chain-loading tool that imposes the setting on itself and then simply chain loads the target program.
I wrote one such utility for the nosh toolset in 2016, that knows the mechanisms for both Linux operating systems and FreeBSD/TrueOS.
oom-kill-protect -- 1000 target-program some-arguments
The -- is there for when someone decides to adapt that to use a negative OOM score. ☺
Further reading
- Jonathan de Boyne Pollard (2016).
oom-kill-protect. nosh toolset. Softwares. - Jonathan de Boyne Pollard (2016-01-31). syslogd(8) with OOM Killer protection. FreeBSD Hackers.