4

I need to start a CPU-intensive system process under low priority so that it doesn't slow down my server. How can I do this on Linux?

This is similar to this question: Start a Java process at low priority using Runtime.exec / ProcessBuilder.start? except on Linux instead of Windows. It's OK if the process's priority is changed after the process is started (as long as there isn't much delay).

Community
  • 1
  • 1
Aleksandr Dubinsky
  • 22,436
  • 15
  • 82
  • 99

1 Answers1

10

Run the command using /usr/bin/nice. For instance:

$ /usr/bin/nice -n 10 somecommand arg1 arg2

will run somecommand arg1 arg2 at a niceness of +10. (In Unix / Linux, a larger niceness value results in a lower scheduler priority. The range of nice is typically from -19 to +19.)

Note that this solution is platform specific. It will only work on Linux and Unix systems ...


FOLLOW UP

The ProcessBuilder should be instantiated as you would any normal command; i.e.

    new ProcessBuilder("nice", "-n", "10", "somecommand", "arg1", "arg2");

There's no black magic about when / how to split commands / arguments. The command (e.g. nice) syntax determines what it arguments should be, and that determines both how they should quoted on the shell command line, and how they should be provided when using ProcessBuilder (or the native exec* syscalls of that matter).

I don't think that there should be problems with waitFor() etc, because (AFAIK) the /usr/bin/nice command uses exec (not fork / exec) to run the supplied command. Try it out ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • How should I pass this to ProcessBuilder? new ProcessBuilder("nice", "-n", "10", "somecommand", "arg1", "arg2") or new ProcessBuilder("nice", "-n", "10", "somecommand arg1 arg2")? Will it be free of any problems with waitfor() and destroy() that the Windows solution exhibited? – Aleksandr Dubinsky Jan 29 '12 at 19:12