Tuesday, April 16, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  5] [ 0]  / answers: 1 / hits: 5353  / 1 Year ago, sun, march 5, 2023, 3:07:05

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?


More From » bash

 Answers
6

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).


[#32907] Monday, March 6, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rvousnove

Total Points: 456
Total Questions: 130
Total Answers: 98

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;