So I have a script that I want to run as root, without hangup and nicely. What order should I put the commands in?
sudo nohup nice foo.bash &
or
nohup nice sudo foo.bash &
etc.
I suspect it doesn't matter but would like some insight from those who really know.
If negative niceness is desired, I would do:
sudo nohup nice command
because according to `info coreutils' nohup should preceed nice. If I want a negative nice value, sudo must come before, since only root is able to use negative nice values.
If positive niceness is desired, I would do simply:
nohup nice sudo command
This ensures that nohup and nice are not run with root privileges.
sudo may not respect niceness. At least, it doesn't on my machine (Ubuntu 9.04). Running this:
nice sudo nice
sudo nice nice
prints out 0 and 10. (Note that 'nice' with no command prints out the current niceness.)
the sudo should go last so that nohup and nice aren't running with root privileges.
so the latter
~ $ sudo nohup nice whoami
nohup: ignoring input and appending output to `nohup.out'
~ $ sudo cat nohup.out
root
The difference between the first and second way you've done it is who owns the nohup.out file. sudo
first will make it owned by root, nohup
before sudo will make it owned by your user.
Disagree with other answers. I recommend:
sudo nohup nice foo.sh
I have observed nohup sudo #fail -- ie nohup is not always transferred to sudo'd sub-sub-processes (this was for certain /etc/init.d scripts on Ubuntu which delegated to yet other scripts). Not sure why, certainly surprising, but was the case and took a good wee while to debug.
(I note others report niceness not being passed through, so seems best to put it last ... although if in doubt on your OS put nice earlier, because nice not taking effect is usually less of a problem than nohup not taking effect!)
Note that sudo nohup leaves nohup.out owned by root, also as has been mentioned, but that's fixed with a:
sudo nohup nice foo.sh >> /tmp/foo.stdout.log 2>> /tmp/foo.stderr.log
I guess all of them do an exec* syscall to pass the ball to the next one, so, whatever the order, it won't leave any hanging processes.
I'd say that nohup should be last so that the two other don't clober the signal handler. (I'm sure nice does not play with signals, but sudo does.)
Then, sudo and nice, it all depends on which way you want to alter the scheduling priority with nice.
- If you want to raise the priority (that is, give a negative value to nice) do sudo before.
- If you want to lower the priority (give nice a positive value) do it before sudo, as you don't need root privileges.