How to keep Linux from hanging up on you

When you run a command in the background on a Linux system and then log out, the process you were running will stop abruptly. If you elect to run the command with a no-hangup command, on the other hand, it will continue running and will store its output in a file.

Here's how this works. The nohup command instructs your process to ignore the SIGHUP signal that would normally shut it down. That allows you to leave time-consuming processes to complete on their own without you having to remain logged in. By default, the output of the command you are running will be left in a file named nohup.out so that you can find your data the next time you log in.

Here’s an example. Say you want to run a search over a huge file system and get a listing of all files that don’t belong to root. And say you don’t want to wait for the command to complete. It’s late and you’re hungry and ready to dash home. You can start the find command with nohup and then head home.

# nohup find / -type f -not -user root -ls &

The next morning when you show up for work, the command will likely be long done and the output file waiting for you.

-rw------- 1 root root 866080760 Jun 20 14:16 nohup.out

One thing you should keep in mind when using nohup is that the output of the command being run will be appended to the previously used nohup.out file if one exists. One way around this is to specify a different file name each time you use the command. The command below will create a file with the year, month (numeric), and day as its name.

# nohup find / -type f -not -user root -ls > `date +%Y%m%d` &

You can run your nohup commands using sudo if you like. Just keep in mind that the output file will be created by default in your current directory and will be owned by root. You can then use the sudo command again to view it.

You can also specify full paths for your output so that it lands in any directory you like.

There are no problems with running multiple nohup commands (i.e., without waiting for the first to finish), though you should be careful to give each output file a different name. And, if you change your mind and want to stop a process that’s running with nohup, you can use a normal kill PID command (sends a SIGTERM, signal 15) or a kill -9 (sends a SIGKILL, signal 9). A process running with nohup is only immune to SIGHUP (signal 1) which is enough to keep it from shutting down when you log off.

The nohup command makes it easy to keep time-consuming processes running even after you log out and maybe even get home while your dinner’s still warm.

Join the Network World communities on Facebook and LinkedIn to comment on topics that are top of mind.

Copyright © 2017 IDG Communications, Inc.