Several ways to enable processes to run reliably in the background under Linux

Source: Internet
Author: User

Want the process to remain running after disconnecting? If the process is already running, how can it be remedied? If there are a large number of such requirements how to simplify the operation?

We often encounter such problems, log on to the remote Linux server with TELNET/SSH, run some long-time tasks, the result of the network instability caused by the task Midway failure. How do i make the command submit without being disturbed by the local shut-down terminal window, network disconnection?

Here are some examples where you can choose different ways to handle this problem for different scenarios.

nohup/setsid/& Scene

What is the easiest way to make sure it runs stably in the background if only a temporary command takes a long time to run?

We know that when the user logs off logout or the network disconnects, the terminal receives a HUP (hangup) signal to close all its child processes. Therefore, our solution has two ways: either let the process ignore the HUP signal, or let the process run in a new session to become a child process that does not belong to this terminal.

1. Nohup

Nohup is undoubtedly the way we think first. As the name implies, Nohup's purpose is to let the submitted command ignore the hangup signal.

The use of nohup is very convenient, just add nohup before the command to be processed, standard output and standard error-deficient capital are redirected to the Nohup.out file. In general, we can add "" at the end & to run the command in the background, or " >filename 2>&1 " to change the default redirect file name.

nohup Example

    1. [[email protected] ~]# nohup ping www.ibm.com &

    2. [1] 3059

    3. nohup: appending output to `nohup.out‘

    4. [[email protected] ~]# ps -ef |grep 3059

    5. root      3059   984  0 21:06 pts/3    00:00:00 ping www.ibm.com

    6. root      3067   984  0 21:06 pts/3    00:00:00 grep 3059

    7. [[email protected] ~]#

2.setsid

Nohup can undoubtedly make our process avoid interruption by ignoring the HUP signal, but if we think in a different way, if our process is not part of the sub-process of the terminal receiving the HUP signal, then naturally it will not be affected by the HUP signal. Setsid can help us do that.

The use of Setsid is also very convenient, just add setsid before the command to be processed.

Setsid Example

  1. [[email protected] ~]# setsid ping www.ibm.com

  2. [[email protected] ~]# ps -ef |grep www.ibm.com

  3. root     31094     1  0 07:28 ?        00:00:00 ping www.ibm.com

  4. root     31102 29217  0 07:29 pts/4    00:00:00 grep www.ibm.com

  5. [[email protected] ~]#

It is worth noting that our process ID (PID) in the example above is 31094, and its parent ID (PPID) is 1 (that is, the Init process ID), not the process ID of the current terminal. Compare this example to the parent ID in the nohup example.

3.&

Here's a little tip about Subshell. We know that the inclusion of one or more names in the "()" allows these commands to run in a child shell, which expands a lot of interesting functionality, and one of the things we're going to talk about right now.

When we put "&" into "()", we will find that the submitted job is not in the job list, that is, it cannot be viewed by jobs. Let's see why it's possible to avoid the effects of HUP signals.

Subshell Example

  1. [[email protected] ~]# (ping www.ibm.com &)

  2. [[email protected] ~]# ps -ef |grep www.ibm.com

  3. root     16270     1  0 14:13 pts/4    00:00:00 ping www.ibm.com

  4. root     16278 15362  0 14:13 pts/4    00:00:00 grep www.ibm.com

  5. [[email protected] ~]#

As can be seen from the example above, the parent ID (PPID) of the newly submitted process is 1 (PID of the Init process) and is not the process ID of the current terminal. Therefore, it does not belong to the sub-process of the current terminal, so it will not be affected by the HUP signal of the current terminal.

Disown

We already know that the effects of HUP signals can be avoided by adding nohup or setsid prior to the command. But if we have already submitted an order without any processing, how can we remedy it to avoid the effects of the HUP signal?

At this time to add nohup or setsid is too late, only through job scheduling and disown to solve the problem.

We can achieve our goal in the following way.

Flexible use of ctrl-z

In our daily work, we can use the ctrl-z to suspend the current process to a background pause, perform some other action, and then use FG to back up the suspended process to the foreground (or BG to put the pending process in the background) to continue running. This allows us to flexibly switch between running multiple tasks within one terminal, which is especially useful when debugging code. Since the code editor is suspended to the background and then re-placed back, the cursor position remains at the location of the last suspension, avoiding the hassle of repositioning.

    • Use disown-h Jobspec to make a job ignore hup signals.

    • Use Disown-ah to make all jobs ignore the HUP signal.

    • Use DISOWN-RH to make the running job ignore the HUP signal.

It is important to note that when disown is used, the target job will be removed from the job list and we will no longer be able to use jobs to view it, but can still find it with PS-EF.

However, there is a problem, the operation of this method is the job, if we run the command at the end of the "&" to make it a job and run in the background, then it is all right, we can use the jobs command to get a list of all jobs.

But if the current command is not running as a job, how can I get its job number? The answer is to use CTRL-Z (hold down the CTRL key while holding down the Z key)!

The purpose of Ctrl-z is to suspend the current process suspend, then we can use the Jobs command to query its job number, and then use the BG Jobspec to put it in the background and continue to run.

It is important to note that this method is used with caution if the suspension affects the running results of the current process.

Disown Example 1 (You can use "disown" directly if you have already used "&" to run the command in the background when you submit the command)

  1. [[email protected] build]# cp -r testLargeFile largeFile &

  2. [1] 4825

  3. [[email protected] build]# jobs

  4. [1]+  Running                 cp -i -r testLargeFile largeFile &

  5. [[email protected] build]# disown -h %1

  6. [[email protected] build]# ps -ef |grep largeFile

  7. root      4825   968  1 09:46 pts/4    00:00:00 cp -i -r testLargeFile largeFile

  8. root      4853   968  0 09:46 pts/4    00:00:00 grep largeFile

  9. [[email protected] build]# logout

Disown Example 2 (if the command was submitted without using "&" to run it in the background, you can use Ctrl-z and "BG" to put it in the background and use "disown")

  1. [[email protected] build]# cp -r testLargeFile largeFile2

  2. [1]+  Stopped                 cp -i -r testLargeFile largeFile2

  3. [[email protected] build]# bg %1

  4. [1]+ cp -i -r testLargeFile largeFile2 &

  5. [[email protected] build]# jobs

  6. [1]+  Running                 cp -i -r testLargeFile largeFile2 &

  7. [[email protected] build]# disown -h %1

  8. [[email protected] build]# ps -ef |grep largeFile2

  9. root      5790  5577  1 10:04 pts/3    00:00:00 cp -i -r testLargeFile largeFile2

  10. root      5824  5577  0 10:05 pts/3    00:00:00 grep largeFile2

  11. [[email protected] build]#

Screen

We already know how to keep the process free of HUP signals, but if there are a lot of such commands that need to be run in a stable background, how do you avoid doing this for every command?

The most convenient way to do this is screen. Simply put, screen provides the ansi/vt100 terminal emulator, which enables it to run multiple full screens of pseudo-terminals under a real terminal. Screen has a lot of parameters and is very powerful, so we'll just describe its common functions and briefly analyze why using screen can avoid the effects of HUP signals.

Using screen is convenient and has several common options:

    • Use the SCREEN-DMS session name to create a session in disconnected mode (and specify its session name).

    • Use Screen-list to list all sessions.

    • Use Screen-r session name to reconnect to the specified session.

    • Use the shortcut key Ctrl-a D to temporarily disconnect the current session.

Screen Example

    1. [[email protected] ~]# screen -dms Urumchi

    2. [[email protected] ~]# screen - list

    3. there is a screens on:

    4.         12842.Urumchi   ( Detached )

    5. 1 Socket in /tmp/screens/s-root.

    6.  

    7. [[email protected] ~]# screen -R Urumchi

When we connect to the screen session with "-R", we can do anything in this pseudo-terminal, no longer worry about the HUP signal will affect our process, and do not have to add "nohup" or "setsid" before each command. What is this for? Let me take a look at the following two examples.

1. Process tree without using the screen's newly process

  1. [[email protected] ~]# ping www.google.com &

  2. [1] 9499

  3. [[email protected] ~]# pstree -H 9499

  4. init─┬─Xvnc

  5.     ├─acpid

  6.     ├─atd

  7.     ├─2*[sendmail]

  8.     ├─sshd─┬─sshd───bash───pstree

  9.     │       └─sshd───bash───ping

As we can see, the bash we're in when we're not using screen is an sshd subprocess, and when SSH disconnects, the HUP signal naturally affects all of the sub-processes underneath it (including our newly created ping process).

2. Process tree using the new process after screen

    1. [[email protected] ~]# screen -R urumchi< /span>

    2. [[email protected] ~]# Ping Www.ibm.com &

    3. [ 1 ] 9488

    4. [[email protected] ~]# pstree -H 9488

    5. init ─┬─ Xvnc

    6.    ├─acpid

    7.   & nbsp ├─ATD

    8.    ├─ screen ─── bash ─── Ping

    9.    ├─ 2 *[ SendMail]

Instead of using screen, bash is the child process of screen, and screen is the child of Init (PID 1). Then when SSH disconnects, the HUP signal naturally does not affect the sub-processes under screen.

Summarize

Now that several methods have been introduced, we can choose different scenarios according to different scenarios. Nohup/setsid is undoubtedly the most convenient method for temporary needs, disown can help us to remedy the job that is currently running, and screen is the choice of a large batch operation.

Read the original

Several ways to enable processes to run reliably in the background under Linux

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.