I want to ensure a script can only be run below a certain nice level. I searched around and I didn't find a good way of doing this, so I came up with this:
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
# use ps to get the niceness of the current process
# only look at the last line of output
# remove whitespace
readonly PRIORITY=$(ps -o '%n' $$ | tail -n 1 | tr -d '[[:space:]]')
if [[ "${PRIORITY}" -lt "10" ]]; then
exit 100
fi
This seems sloppy to me, it would be nice if there was a more simple way of doing this. I guess I really just want a tiny program that returns the current process's scheduling priority, but I don't want to write the 3 lines of c code myself :-/
Documentation of the GNU coreutils nice
command:
Usage: nice [OPTION] [COMMAND [ARG]...]
Run
COMMAND
with an adjusted niceness, which affects process scheduling. With noCOMMAND
, print the current niceness.
However, beware that
NOTE: your shell may have its own version of nice, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports.
In case your shell does have such a builtin with different behavior, you'd want to use the usual techniques for running a binary rather than builtin.