In Linux, if you want to run the process in the background, we usually add & to the end of the command. In fact, the command is put into a Job Queue:
$./Test. Sh & [1] 17208 $ jobs-L [1] + 17208 running./test. Sh &
For commands that have been executed in the foreground, you can also re-execute them in the background.CTRL + zPause a running process, and then useBGCommand to run the stopped job in the background:
$. /Test. sh [1] + stopped. /test. sh $ BG % 1 [1] +. /test. sh & $ jobs-L [1] + 22794 running. /test. sh &
However, for processes executed from the top to the backend, the parent process is still the shell process of the current terminal. Once the parent process exits, The hangup signal is sent to all sub-processes, the child process also exits after receiving the hangup. If we want to continue running the process when exiting the shell, we need to useNohupIgnore the hangup signal, orSetsidSet the parent process as the INIT process (process number 1)
$ Echo $21734 $ nohup. /test. sh & [1] 29016 $ PS-Ef | grep test515 29710 21734 0 00:00:00 pts/12/bin/sh. /test. sh515 29713 21734 0 00:00:00 pts/12 grep Test
$ Setsid./test. Sh & [1] 409 $ PS-Ef | grep test515 410 1 0? 00:00:00/bin/sh./test. sh515 413 21734 0 00:00:00 pts/12 grep Test
The above test demonstrates that the process is run in the background with nohup/setsid and is not affected by the current shell exit. So what should we do for processes that are already running in the background? AvailableDisownCommand:
$. /Test. sh & [1] 2539 $ jobs-L [1] + 2539 running. /test. sh & $ disown-H % 1 $ PS-Ef | grep test515 410 1 0 11: 49? 00:00:00/bin/sh./test. sh515 2542 21734 0 00:00:00 pts/12 grep Test
Another method is to execute a process in a subshell, which is similar to setsid. The method is simple. Enclose the command in parentheses:
$ (./Test. Sh &) $ PS-Ef | grep test515 410 1 0 :49? 00:00:00/bin/sh./test. sh515 12483 21734 0 00:00:00 pts/12 grep Test