How to run processes in the background in Linux

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.