Linux – How to renice all threads (and children) of one process on Linux

linuxniceprocessthread

Linux does not (yet) follow the POSIX.1 standard which says that a renice on a process affects "all system scope threads in the process", because according to the pthreads(7) doc "threads do not share a common nice value".

However, sometimes, it can be convenient to renice "everything" related to a given process (one example would be Apache child processes and all their threads). So,

  • how can I renice all threads belonging to a given process ?
  • how can I renice all child processes belonging to a given process ?

I am looking for a fairly easy solution.

I know that process groups can sometimes be helpful, however, they do not always match what I want to do: they can include a broader or different set of processes.

Using a cgroup managed by systemd might also be helpful, but even if I am interested to hear about it, I mostly looking for a "standard" solution.

EDIT: also, man (7) pthreads says "all of the threads in a process are placed in the same thread group; all members of a thread group share the same PID". So, is it even possible to renice something which doesn't have it's own PID?

Best Answer

You can use /proc/$PID/task to find all threads of a given process, therefore you can use

$ ls /proc/$PID/task | xargs renice $PRIO

to renice all threads belonging to a given process.

Same way /proc/$PID/task/$PID/children can be used to find all child processes (or /proc/$PID/task/*/children if you want all child processes of all threads of a given process).

$ cat /proc/$PID/task/$PID/children | xargs renice $PRIO
$ cat /proc/$PID/task/*/children | xargs renice $PRIO
Related Question