After Putty is disabled, the background program continues to run-use screen to manage your remote sessions

Source: Internet
Author: User

Do you often need SSH or Telent to remotely log on to the Linux server? Do you often have a headache for long-running tasks, such as system backup and FTP transmission. Generally, we open a remote terminal window for each such task because it takes too long to execute. You must wait for the task to complete. During this period, you cannot close the window or disconnect the connection. Otherwise, the task will be killed and everything will be abandoned.

Culprit: sighup Signal

Let's see why closing the window or disconnecting will cause the running program to die.

Linux/Unix has the following concepts:

  • Process Group: A collection of one or more processes. Each process group has a unique process group ID, that is, the ID of the Process leader process.
  • Session: a set of one or more process groups. It has a unique session leader ). The ID of the first process.
  • A single control terminal (controlling terminal) is available during the session ). The first process connecting to the control terminal is called the control process ). The process currently interacts with the terminal is called the foreground process group. Other process groups are called background process groups.

According to posix.1:

  • The default action of sighup is to terminate the program.
  • When the terminal interface detects that the network connection is disconnected, it sends the hanging signal to the control process (the first process in the session ).
  • If the first process of the session ends, the signal is sent to the foreground Process Group of the session.
  • When a process exits and an orphan process group is generated, if any process in the orphan process group is in the Stop state, the sighup and sigcont signals are sent to all processes in the process group.

Therefore, when the network is disconnected or the terminal window is closed, the control process receives the sighup signal and exits, causing other processes to exit during the session period.

Let's look at an example. Open two SSH terminal windows and run one of the top commands.

[root@tivf09 root]# top

 

In another terminal window, find the top process ID is 5180, and its parent process ID is 5128, that is, log on to shell.

[root@tivf09 root]# ps -ef|grep toproot      5180  5128  0 01:03 pts/0    00:00:02 toproot      5857  3672  0 01:12 pts/2    00:00:00 grep top

 

Use the pstree command to see the relationship more clearly:

[root@tivf09 root]# pstree -H 5180|grep top|-sshd-+-sshd---bash---top

 

Run the PS-XJ command. You can see that the login shell (PID 5128) and top are in the same session period. shell is the first process in the session period and the pgid of the Process Group is 5128, the pgid of the top process group is 5180, which is the foreground process group.

[root@tivf09 root]# ps -xj|grep 5128 5126  5128  5128  5128 pts/0     5180 S        0   0:00 -bash 5128  5180  5180  5128 pts/0     5180 S        0   0:50 top 3672 18095 18094  3672 pts/2    18094 S        0   0:00 grep 5128

 

Close the first SSH window. In the other window, you can see that the top is also killed.

[root@tivf09 root]# ps -ef|grep 5128root     18699  3672  0 04:35 pts/2    00:00:00 grep 5128

 

If we can ignore the sighup signal, closing the window will not affect the running of the program. The nohup command can achieve this purpose. If the program's standard output/standard error is a terminal, nohup redirects it to the nohup. Out file by default. It is worth noting that the nohup command only causes the program to ignore the sighup signal and also requires the flag&Run it in the background.

nohup <command> [argument…] &

 

Although nohup is easy to use, it is still relatively "simple". It can handle simple commands and is troublesome for complicated tasks that require human-computer interaction.

In fact, we can use a more powerful utility screen. Popular Linux distributions (such as Red Hat Enterprise Linux 4) usually come with screen utilities. If not, you can download them from the GNU screen official website.

[root@tivf06 ~]# rpm -qa|grep screenxscreensaver-4.18-5.rhel4.11screen-4.0.2-5

 

Start using screen

To put it simply, screen is a window manager that can reuse a physical terminal among multiple processes. Screen has the concept of session. You can create multiple screen Windows in one screen session, just like operating a real Telnet/SSH connection window in each screen window. There are several ways to create a new window in screen:

1. Directly type the screen command in the command line.

[root@tivf06 ~]# screen

 

Screen creates a full screen window for executing shell. You can execute any shell program, as in the SSH window. In this window, type exit to exit the window. If this is the only window of the screen Session, the screen session will exit; otherwise, the screen will automatically switch to the previous window.

2. The screen command is followed by the program you want to execute.

[root@tivf06 ~]# screen vi test.c

 

Screen creates a single window session for executing VI test. C. Exit VI and exit the window/session.

3. Create a screen session in both of the preceding methods. We can also create a new window in an existing screen session. In the current screen window, TypeC-a c, That is, press Ctrl + A, and then press C. Screen generates a new window in the session and switches to the window.

Screen also has more advanced features. You can temporarily disconnect (detach) the screen session without interrupting the running of the program in the screen window, and re-Connect (attach) The session at a later time to re-control the program running in each window. For example, open a screen window to edit the/tmp/ABC file:

[root@tivf06 ~]# screen vi /tmp/abc

 

Then we want to temporarily exit and do something else, such as going out for a walk, then type in the screen windowC-a d, Screen will give the detached prompt:

Temporarily interrupt session

After half an hour, I came back and found the screen session:

[root@tivf06 ~]# screen -lsThere is a screen on:        16582.pts-1.tivf06      (Detached)1 Socket in /tmp/screens/S-root.

 

Reconnect session:

[root@tivf06 ~]# screen -r 16582

 

Let's see what happened. It's great. Everything is there. Continue.

You may notice that a special key combination C-A is used to send commands to screen. This is because the information we typed on the keyboard is directly sent to the current screen window, you must use other methods to send a command to the screen window manager, by default, screen receives commands starting with C-. This command form is called Key Binding in screen, and C-A is called command character ).

You can useC-a ?To view all key bindings. common key bindings include:

 

C-? Show all key binding information
C-A W Show list of all windows
C-a c- Switch to the previously displayed window
C-A C Create a new window for running shell and switch to it
C-A N Switch to the next window
C-A P Switch to the previous window (opposite to C-a n)
C-A 0 .. 9 Switch to window 0 .. 9
C- Send C-A to the current window
C-a d Temporarily disconnect screen session
C-A K Kill current window
C-[ Enter copy/rollback Mode

 

Screen common options

Use the key to bind C-? The default command key is c-a, and the Escape Character C-A (literal ^ A) is:

Screen common options

Because screen regards C-A as the beginning of the screen command, if you want the screen window to receive the C-a character, enter C-. Screen also allows you to use the-E Option to set your own command characters and escape characters. The format is:

-Exy X is the command character and Y is the character of the escape command character

The screen session started by the following command specifies that the command character is c-t, and the escape c-t character is T, through c-t? Command to see the change.

[root@tivf18 root]# screen -e^tt

Custom command characters and escape characters

Other common command options include:

 

-C file Use the configuration file instead of the default $ home/. screenrc
-D |-d [pid. TTY. Host] Instead of starting a new screen session, you can disconnect other running screen sessions.
-H num Specify the buffer size for historical rollback as num rows
-List |-ls List existing screen sessions in the format of PID. TTY. Host
-D-m Start a session in disconnected Mode
-R sessionowner/[pid. TTY. Host] Reconnect to a disconnected session. To connect to screen sessions of other users in multi-user mode, you must specify the sessionowner and set the setuid-root permission.
-S sessionname Specify a name for the session when creating a screen session
-V Display screen version information
-Wipe [Match] Same-list, but delete sessions that cannot be connected

 

In the following example, two screen sessions in the detached state are displayed. You can use screen-r <screen_pid> to reconnect to the screen:

[root@tivf18 root]# screen –lsThere are screens on:        8736.pts-1.tivf18       (Detached)        8462.pts-0.tivf18       (Detached)2 Sockets in /root/.screen.[root@tivf18 root]# screen –r 8736

 

If one of the sessions is killed for some reason (for example, manually killing the Session), screen-List displays the session as dead. Run the screen-Wipe command to clear the session:

[root@tivf18 root]# kill -9 8462[root@tivf18 root]# screen -ls  There are screens on:        8736.pts-1.tivf18       (Detached)        8462.pts-0.tivf18       (Dead ???)Remove dead screens with 'screen -wipe'.2 Sockets in /root/.screen.[root@tivf18 root]# screen -wipeThere are screens on:        8736.pts-1.tivf18       (Detached)        8462.pts-0.tivf18       (Removed)1 socket wiped out.1 Socket in /root/.screen.[root@tivf18 root]# screen -ls  There is a screen on:        8736.pts-1.tivf18       (Detached)1 Socket in /root/.screen.[root@tivf18 root]#

 

The-D-M option is an interesting partner. They start a session in disconnected mode. You can connect to the session as needed later. Sometimes this is a very useful function. For example, we can use it to debug background programs. This option is more commonly used:-DMs sessionname

Start an initial disconnected screen session:

[root@tivf06 tianq]# screen -dmS mygdb gdb execlp_test

 

Connect to this session:

[root@tivf06 tianq]# screen -r mygdb

 

Manage your remote sessions

Let's take a look at how to use screen to solve the sighup problem. For example, we want to transfer a large file over FTP. If you follow the old method, log on to the system via SSH and run the FTP command to start transmission .. If the network speed is okay, congratulations, you don't have to wait too long. If the network is not good, wait honestly. You can only disconnect the SSH connection after the transmission is complete. Let's try using screen.

Log on to the system through SSH and Type Screen in the command line.

[root@tivf18 root]# screen

 

In the screen shell window, enter the FTP command, log on, and start transmission. Don't you want to wait? OK. In the window, type C-A D:

Manage your remote sessions

Then .. Log out of SSH? As you do, just don't kill the screen session.

Is it convenient? Furthermore, we can use screen to manage your remote sessions and save all your work content. Do you have to open many windows every time you log on to the system, and then open them again every day? Let screen help you "save". You only need to open an SSH window and create a screen window. When you exit, C-a d will "save" your work, after the next login, you can directly use screen-r <screen_pid>.

It is better to give a name for each window so that you can remember it. Use C-A to name the window. Use C-a w to view the names of these windows. The names may appear in different positions. Use Putty:

Putty

Use telnet:

Telnet

 

More screen Functions

Screen provides rich and powerful customization functions. You can configure the files/etc/screenrc and $ home/by default in screen /. specify more in screenrc, such as setting screen options, customizing binding keys, setting screen session self-start Windows, enabling multi-user mode, and customizing user access permission control. If you want to, you can also specify the screen configuration file.

Taking the multi-user function as an example, screen runs in single-user mode by default. You need to specify multiuser on in the configuration file to enable multi-user mode, through ACL * (acladd, acldel, aclchg ...) command, You can flexibly configure other users to access your screen session. For more information about the configuration file, see the man page of screen.

References

  • "Advanced Programming in the Unix environment: Second Edition" W. Richard Steven S, Stephen A. Rago provides more information about Linux/Unix process relations and signals.
  • GNU screen Official Website: http://www.gnu.org/software/screen/
  • Screen man page provides the most detailed information: http://www.slac.stanford.edu/comp/unix/package/epics/extensions/iocConsole/screen.1.html

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.