Linux and Command-Line Basics
On a server reached over SSH, a long-running task was started with "./run.sh &", and when the connection was closed the task stopped too. Which of the following is the most appropriate way to start it so that it keeps running after the connection is closed?
- A./run.sh > run.log 2>&1 &
- Bnice -n 19 ./run.sh > run.log 2>&1 &
- Cnohup ./run.sh > run.log 2>&1 &
Show answer and explanation
Answer: C. nohup ./run.sh > run.log 2>&1 &
When the connection is lost, SIGHUP, which reports that the terminal has hung up, is sent to the shell, and shells such as bash also send SIGHUP to their jobs. The default action on receiving SIGHUP is to exit, so background jobs stop as well. nohup starts the command so that it ignores SIGHUP, and with its output directed to a file, the task keeps running after the connection is closed. If it is started from a terminal without redirecting the output, nohup writes the output to a file called nohup.out. Another common approach is to use a tool such as tmux or screen, which keeps the terminal session alive on the server and lets you reattach to it later.
- A. Directing the output to a file does not stop the task from exiting when it receives SIGHUP.
- B. nice -n 19 only starts the task with a lower priority and does not change how it reacts to SIGHUP.
- C. Correct. nohup makes it ignore SIGHUP, and the output is kept in a file.