Linux tips: A reliable way to keep processes running in the background

Source: Internet
Author: User

Original link: http://www.ibm.com/developerworks/cn/linux/l-cn-nohup/

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 time-consuming tasks, and the result is a failure in the middle of the task due to network instability. How is it
Let the command submit after the local Shut down Terminal window/network disconnect interference? Here are some
example, you can choose different ways to handle this problem for different scenarios.

Hangup the name of the
In earlier versions of Unix, each terminal would be
Modem and System communication. When the user logout,
The modem hangs up on the phone. With
When the modem disconnects, it gives the terminal
Send a hangup signal to notify it to close all Wahabbi
Ride.

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?
Workaround:
We know that when the user logs off (logout) or the network is disconnected, the terminal receives
HUP (Hangup) signal to close all of its child processes. Therefore, our solution
There are two ways of doing this: either let the process ignore the HUP signal or let the process run in the new
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. Let me
Let's take a look at Nohup's help information:

NOHUP (1) User Commands NOHUP (1-run a command immune to hangups, with output to a non-Ttysy Nopsisnohup command [arg]...nohup optiondescriptionrun command, ignoring hangup signals. --help display this help andexit--versionoutput version information and exit

It can be seen that the use of nohup is very convenient, just add nohup before the command to be processed, standard output and standard error lack of capital
is redirected to the Nohup.out file. In general, we can add "&" at the end to run the command in the background, but also
Use ">filename 2>&1" to change the default redirect file name.

nohup Example

[Email protected] ~]# NohupPingWww.ibm.com &[1]3059nohup:appending output to ' Nohup.out'[Email protected] ~]#PS-ef |grep 3059Root3059 984 0  +: .pts/3 xx:xx:xx PingWww.ibm.comroot3067 984 0  +: .pts/3 xx:xx:xx grep 3059[[Email protected]~]#

2. Setsid

Nohup can undoubtedly prevent our process from being interrupted halfway by ignoring the HUP signal, but if we think in a different way, if we

Process does not belong to the sub-process of the terminal receiving the HUP signal, then naturally it will not be affected by the HUP signal. Setsid will be able to help
Help us do that. Let's take a look at Setsid's help information:

Setsid (8) Linux Programmer ' s Manual setsid (8 in a new session.

Visible Setsid is also very convenient to use, but also only need to deal with the command before adding Setsid can.

Setsid Example

[Email protected] ~]# SetsidPingWww.ibm.com[[email protected]~]#PS-ef |grepWww.ibm.comroot31094 1 0  -: -?xx:xx:xx PingWww.ibm.comroot31102 29217 0  -: inpts/4 xx:xx:xx grepWww.ibm.com[[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) and does not
is 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 be
In the shell, which expands a lot of interesting features, we're going to talk about one of them now.
When we put "&" into "()", we will find that the submitted job is not in the job list, i.e.
Jobs to look at. Let's see why it's possible to avoid the effects of HUP signals.

Subshell Example

[Email protected] ~]# (PingWww.ibm.com &) [[email protected]~]#PS-ef |grepWww.ibm.comroot16270 1 0  -: -pts/4 xx:xx:xx PingWww.ibm.comroot16278 15362 0  -: -pts/4 xx:xx:xx grepWww.ibm.com[[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

Scene:
We already know that the effects of HUP signals can be avoided by adding nohup or setsid prior to the command. But if we don't
Any processing has already submitted the order, how to remedy it to avoid the impact of HUP signal?

Workaround:
At this time to add nohup or setsid is too late, only through job scheduling and disown to solve the problem. Let's see.
A little help with disown's information.

 Disown [-ar ] [-h] [Jobspec ...] Without options, each jobspec was removed from the table ofactive jobs.  If the -h option is given, and each jobspec are notremoved from the table, but was marked so That SIGHUP was notsent to the job  if   the shell R Eceives a SIGHUP. If no Jobspecis present, and neither the -a nor the-r option is supplied,the current Job is used. If no Jobspec is supplied, the -aoption means to remove or mark all jobs; the - r option withouta jobspec argument restricts operation to running jobs. Thereturn value is  0   unless a jobspec does not Specify a validjob.  

The

can see that we can achieve our goal in the following way. The
uses disown-h jobspec to make a job ignore hup signals. The
uses Disown-ah to make all jobs ignore the HUP signal. The
uses DISOWN-RH to make the running job ignore the HUP signal.

Flexible use ctrl-z
in our daily work, we can use Ctrlz to suspend the current process to the background and suspend the operation, holding
, and then use FG to put the pending process back in the foreground (also available with BG to suspend
The process of span style= "Text-decoration:underline" > is placed in the background) continues to run. This way we will
can be flexibly switched on in one terminal to run multiple any
service, which is especially useful when debugging code. Because
suspends the code editor to the background and then back on,
cursor positioning still stuck at last suspend,
avoids the hassle of repositioning .

It is important to note that when disown is used, the target job will be taken from the job list
, we will no longer be able to use jobs to view it, but we can still use Ps-ef
To find it.
But there is also the problem that this method of manipulating objects is jobs, if we are running a life
Add "&" at the end to make it a job and run in the background, then everything
We can get a list of all the jobs by the jobs command. But if
Does not run the current command as a job, how can I get its job number? The answer is to use CTRL-Z (hold down the CTRL key while
Hold down the z key)!

The purpose of Ctrl-z is to suspend the current process (Suspend), and then we can use the Jobs command to query its job number, and then
Use BG Jobspec to put it in the background and continue running. It is important to note that if a suspension affects the running results of the current process, be cautious
Use this method.

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)

[Email protected] build]#CP-R testlargefile Largefile &[1]4825[email protected] build]# jobs[1]+ RunningCP-i-r testlargefile Largefile &[email protected] build]# disown-H%1[email protected] build]#PS-ef |grepLargefileroot4825 968 1  the: $pts/4 xx:xx:xx CP-I.-R testlargefile Largefileroot4853 968 0  the: $pts/4 xx:xx:xx grepLargefile[[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,
Then use "Disown")

[Email protected] build]#CP-R testlargefile largefile2[1]+ StoppedCP-I.-R testlargefile largefile2[[email protected] build]# BG%1[1]+CP-i-r testlargefile LargeFile2 &[email protected] build]# jobs[1]+ RunningCP-i-r testlargefile LargeFile2 &[email protected] build]# disown-H%1[email protected] build]#PS-ef |grepLargefile2root5790 5577 1 Ten:Genevapts/3 xx:xx:xx CP-I.-R testlargefile Largefile2root5824 5577 0 Ten: topts/3 xx:xx:xx grepLargefile2[[email protected] build]#

Screen
Scene:
We already know how to get the process out of the HUP signal, but if there are a lot of these commands that need to run in a stable background, such as
How do you avoid doing this for every command?
Workaround:
The most convenient way to do this is screen. Simply put, screen provides a ansi/vt100 terminal emulator that enables it to be
Run multiple full-screen pseudo-terminals under a real-world terminal. Screen has a lot of parameters and is very powerful, and we're just here to introduce
Can and briefly analyze why using screen can avoid the effects of HUP signals. Let's take a look at screen's help information:

Screen (1) Screen (1) Namescreen-Screen manager with Vt100/ANSI terminal Emulationsynopsisscreen [-Options] [cmd [args]]screen-R [[PID.] Tty[.host]]screen-R sessionowner/[[PID.] Tty[.host]]descriptionscreen is a full-Screen window manager, that multiplexes a physicalterminal between several processes (typically interactive shells). Each virtual terminal provides the functions of a DEC VT100 Terminaland,inchaddition, several control functions from the ISO6429(ECMA -, ANSI X3. -) and ISO2022Standards (e.g. insert/Delete line Andsupport formultiple character sets). There is a scrollback HistoryBuffEr forEach virtual terminal and a copy-and-paste mechanism Thatallows moving text regions between windows.

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

[Email protected] ~]# screen-~]# screen-listthere are a screen on:12842. Urumchi (Detached)1 in/tmp/screens/s-~]# screen-r Urumchi

When we connect to the screen session with "-R", we can do whatever we want in this pseudo-terminal and never worry about the HUP signal
Our process has an impact, and we don't have to add "nohup" or "setsid" to each command. What is this for? Let me have a look.
Here are two examples of it.

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

Ping www.google.com &[194999499  init─┬─xvnc├─acpid├─atd├─2*[sendmail]├─sshd─┬─sshd───bash───pstree│└─sshd───bash─── Ping

We can see that the bash we're in when we're not using screen is a subprocess of sshd, and when SSH disconnects, the HUP signal naturally
Affects all of the sub-processes below it, including our newly created ping process.

2. Process tree using the new process after screen

[[Email protected] ~]# screen-ping www.ibm.com &[19488  9488 init─┬─xvnc├─acpid├─atd├─screen───bash─── Ping ├─ 2*[sendmail]

Instead of using screen, bash is the child process of screen, and screen is the child of Init (PID 1). That
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 a temporary need
The most convenient way, disown can help us to remedy the job that is currently running, while screen is in bulk operation
The choice of the time is not two

===========================================================

Linux tips: A reliable way to keep processes running in the background

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.