When we execute a command in Linux, it will create our process in the background and assign a unique process ID. This process can be ended in three ways
- The assigned task is completed
- You explicitly terminate the process
- You log out, or in the case of SSH, the connection is disconnected and the session is terminated
Imagine that you are running a critical process, you may need to log out urgently or disconnect, the process will stop immediately, and you may lose your work.
To avoid this situation, we can use the nohup
command. nohup
executes other commands specified in the parameters in Linux. This command ignores all SIGHUP
(hang up) signals. When its controlling terminal is closed, SIGHUP
is sent to the process.
For a better understanding, let's look at the grammar.
nohup COMMAND [ARGS]
Run commands in the foreground
nohup
will run in the foreground, and the output of the command will be stored in the nohup.out
file. The nohup
command will create this file in the current directory. If the user does not have sufficient permissions to write files in the current directory, nohup
will generate output files in the home directory
Let's look at the sample output:
root@elephdev.com:/# MYCOMMAND="echo'My name is Elephdev.'"
root@elephdev.com:/# nohup $MYCOMMAND
nohup: ignoring input and appending output to'nohup.out'
When we cat
looked at the content of the output file, we saw this
root@elephdev.com:/# cat nohup.out
'My name is Elephdev'
We used a small command, so it will be executed immediately. For the extended process, you can log off at this time and the process will still run
Run commands in the background
Well, we can also run this command in the background. To run it in the background, we use the &
operator
If we run the same command in the background, we will get the following output
root@elephdev.com:/# MYCOMMAND="echo'My name is Elephdev.'"
root@elephdev.com:/# nohup $MYCOMMAND &
[1] 24
root@elephdev.com:/# nohup: ignoring input and appending output to'nohup.out'
The integer you see in the output is the process ID.
You can also use the process ID to terminate this background process.
kill -9 24
Post comment 取消回复