What is the life of an infinite loop send to background?
Matthew Barrera
When will an infinite loop end?
E.g. if I run
while :; do sleep 1; date +%s; done &when will this end — on closing the terminal or on shutdown?
2 Answers
When you provide & at the end, it goes into the background. Whether it is killed or not depends on how you close the terminal.
If you close the terminal application itself (Ctrl+F4, press the x in the window decoration, or Shift+Ctrl+W for gnome-terminal), it kills the background process.
But if you close the terminal using exit or Ctrl+D, it continues to run, even if you log out (unless it is a GUI application). It will end when you shut down.
(I do not know why there is a difference between the two. I suspect that when you close the application, the operating system closes it and its children.)
The following is different:
nohup while :; do sleep 1; date +%s; done &The nohup command detaches it from the terminal. However you close the terminal, the command will continue to run until you shut down (logging out is not sufficient) or kill the command manually.
When you use nohup, the output goes to ~/nohup.out unless you manually redirect the output.
P.S. The command will not work with nohup as given, because nohup does not take a compound command. But you could script it and run the script with nohup.
P.P.S. It is easier to see what is going on by running a GUI. Instead of the while… command, I run this:
gcalctool &Much quicker and easier to see what is happening, as the calculator disappears when it is killed; and you can kill it easily (just close the calculator).
9If you supply & a the end, closing the terminal will not close the process. It can still be killed by a TERM or KILL signal, though. On shutdown, TERM and KILL are sent to all the processes.