Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
In our work, we may often have to run programs on the server. The programs may be time-consuming and need to be run for a period of time. We hope that the program will continue to run even if the terminal is closed. The nohup command in Linux can do this.
Nohup is the abbreviation of English no hangup, which means that the program does not exit. It is used to run commands in the background of the system without hanging up, and exit the terminal will not affect the operation of the program.
The nohup command will be used in more detail.
Command syntax
Nohup Command parameters Nohup optionCopy the code
Options:
--help # Displays the help information and exits --version # displays the version information and exitsCopy the code
The sample
Here is a test.py program that prints “Hello nohup!” every two seconds. :
import time
while True:
print("hello nohup!")
time.sleep(2)
Copy the code
Then use thenohup python3 test.py
Run.
Note: When using the nohup command, the output of the program is redirected to a nohup.out file by default. If we want to output to the specified file, we can specify another output file: nohUP python3 test.py > out.txt
In fact, up to now, there is no real program to run in the background, terminal closed not affected!
If you want the program to actually run in the background, you can add ampersand.
nohup python3 test.py > out.txt &
Copy the code
Close the terminal, open it again, and use the ps command to check the process. You will find that the program is still running.
PSH @ deepin - PC: ~ / Desktop/test $ps - aux | grep python PSH 36313 17768 8120 0.0 0.2? S 16:25 0:00 python3 test.pyCopy the code
Here, if you want to redirect both standard error and standard output to the specified out.txt file, you can use the 2>&1 symbol. The 2>&1 symbol means that standard error 2 will be redirected to standard output &1.
- 0 stdin (standard input)
- 1 stDout (standard output)
- 2 Stderr (Standard error)
nohup python3 test.py > out.txt 2>&1 &
Copy the code
The nohup command combined with the ampersand enables processes to run in the background, even when the terminal is shut down.
If you want to terminate the process, what do you do? Check out the previously shared article: Several ways to kill a process in Linux.
Original is not easy, if small partners feel helpful, please click a “like” and then go ~
Finally, thank my girlfriend for her tolerance, understanding and support in work and life!