Question: I started the process and move a process to background by using bg command or Ctrl+z or ampersand symbol (&) from the terminal. But when I am closed the terminal that also terminates the background process. How to I ensure that the background processes is not terminated even after i close the terminal?
Solution:
Most of the time you running process in background in the terminal via bg or Ctrl+z or ampersand symbol (&). If you start a command and you closed the terminal, the process / command will get killed. This is because Linux Operating System, by default will end the process if you exit your terminal. Sometime the job or command takes a long time , it is not secure to let your terminal open while you are not there, or maybe not possible to let it open if you are over a running process in background, so you may want to use nohup command to let the process running even when you exit your terminal. If you are not sure when the job will finish, then it is better to leave job running in background. However, if you logout the system, the job will be stopped. What do you do? For this use any one of the command to run process in background even if you exit from terminal or logout from your session.
1. use the “screen” command
2. use the “nohup” command
3. use the “disown” command
1. The “screen” utility: Just open a shell terminal and type screen -ls . You get the name(s) of the screen session-terminal(s) where a process was set to be run in back-ground (bg) . Now use “screen -R session-terminal name ” and BINGO , you can manipulate the process if it is still running (not finished his job).
2. The “nohup” utility is an ” out of the box” utility , just run any command but in front set the keyword “nohup“ example : nohup cat /dev/zero > /dev/null &
Be sure to add the & sign so the command is executed in background. Now even if the terminal is closed , the process / command will continue to run . Just open a new terminal and run :
ps -aux |grep nameof-command (ps aux |grep cat ) and BINGO you get the PID of the process.
3. The “disown” command has the same functionality but is implemented differently .
Just enable a process to run in the background with the & . The terminal will assign a job-ID to this process , let’s say 5065 . Now use disown 5065 , and the process will be inherited by the init process , so even if the terminal is closed the process will keep running.
How does disown and nohup commands work?
What they do is that they connect all your process to the parent process of the computer which happens to be init (the parent process of all process running on the computer). Viewing all the process on the computer, use pstree command , the init is first (root of the inverted tree) process which radiates all the other process in the computer. Now if you run the top command you will see all the processes that were manipulated with disown and nohup with a PPID of 1 (init) .
0 comments:
Post a Comment