[The powerful screen command in turn]linux

Source: Internet
Author: User
Tags exit in session id sessions


[The powerful screen command in turn]linux


http://pythonorg.diandian.com/post/2012-01-05/40027464147






Today with screen with a point of birth, there are several features do not know how to use, Internet search, a friend wrote a very fine, to this brother salute, I turned away here, for future use. Because there are several useful functional articles are not described in the article. I will give a pre-supplement at the end of the reprint. The following reprint begins



Reprint Address: http://hi.baidu.com/nkhzj/blog/item/9de2cdfdddf0db42d7887d42.html



Today, I found a "baby", which is the Linux screen command, for remote login, not only provides a nohup-like function, but also provides my favorite "multiple desktop" features.



Usually open a putty telnet, often need to switch back and forth between two programs, how to do? Ctrl-z and FG, BG? These are too much trouble. In fact, we can use the screen command to achieve easy and convenient switching.



I mainly refer to the following two articles (attached to the end), my own summary of the method is:




"First create a session with the screen [-s] command, and then you can create multiple windows in the session." Use screen [-s] to create multiple sessions, and each session can create multiple windows. You can switch between different windows with commands such as Ctrl-a n/p. If you want to switch between sessions, you need to ctrl-a D back to the login session (like the root of a big tree), and then use the SCREEN-LS to see what session you have, then using SCREEN-R to decide which session to revert to. For already attached session can not direct screen-r, need first screen-d, then can Screen-r "









"Reprint 1"



System administrators often need to telnet to the server
Then run some programs on the server
There was a time
Have to run for a long time (more than 12 hours)
This is if the program does not end, exit the remote management terminal
The remote-running program is likely to be lost.
The usual workaround is to use the command nohup
But Nohup also has a lot of problems.
When you have the screen
It's all gone.
Typing command screen
Creates a single window running the shell.
In the face of it
You can run the program you need.
Then CTRL + A to exit the window you just created (back to the environment before screen)
And then typing the command screen to create a new terminal window
That's it
You can create multiple windows with Shell (these windows can run your own application)
This is where you exit the Remote Administration window (the environment into screen)
The Windows in your screen window won't close.
It's not going to be a natural application.
With Screen-ls you can see all the screen sessions
Use Screen-r SessionID to enter the specific screen session specified by the SessionID
When the last screen session is no longer in use
Screen-r SessionID in.
Exit exits



Unix/linux Tools: The screen command uses
Screen use
Using screen is very easy. Simply type screen in the shell to open a screen session.
Under each screen session, all commands start with Ctrl + A (C-A).
Now let me briefly introduce the basic commands.
C-a C-Create to open a new window
C-a N-Next, switch to next window
C-a P--Previous, previous window
More..
C-a c-a, other, switch between two windows
C-a W-Windows, lists the windows that are turned on that have those
C-a 0, switch to window No. 0
C-a 1..9, switch to the first 1..9 window
C-a A, c-a, in Emacs, VE, bash, tcsh can be moved to the beginning of the line
C-a T-time, showing the current times, and the system's load
C-a K (uppercase), kill window, forcibly closes the current window
c-a [, enter copy mode, you can roll back, search,
Replication is like using VI
C-b Backward,pageup
C-f Forward,pagedown
H (uppercase) high, move the cursor to the upper-left corner
L Low, move the cursor to the lower left corner
0 move to the beginning of the line
$ End of line
W forward one word, move forward in words
b Backward One word, move backward in words
Space is first pressed as the starting point for the marked area, and the second press is the end point
ESC ends Copy Mode
C-A], Paste, paste the content you just selected in copy mode
C-a? Help, show simple instructions
C-a D-Detach, will present the screen session (may contain multiple Windows)
Throw it into the background. When you press C-a D to detach the screen session, it will return to the state that is not yet in screen, and the process (either foreground/background) that is running within each window in the screen session continues to execute , even if the logout is not affected.
The next time login comes in:
Screen-ls, show all screen sessions
screen-r [keyword], select a screen session Resume dialog
If there is attached sessions in Screen-ls:
screen-d [keyword],force detach to "take over".



Instance:
The explanation has looked so much, let us use a practical example to end our study today.
After we open a screen and then use Joe to edit a file, you can run CTRL + A as soon as you need to leave, as shown below:
[Email protected] becks]$ screen
[Detached]
This time when we run PS-E can see PTS/2 this I just ran the screen is running Joe
6264 PTS/2 00:00:00 Bash
6354 PTS/2 00:00:00 Joe
And when we come back and want to restore this session, just type Screen-r, and when you have multiple sessions, you will be prompted to select one, as follows:
[Email protected] becks]$ Screen-r
There is several suitable screens on:
6263.pts-1.ec-base (Detached)
6382.pts-1.ec-base (Detached)
Type "screen [-d]-R [PID.] Tty.host "to resume one of them.
Enter the PID of the session to restore
[Email protected] becks]$ screen-r 6263
To exit the session of screen, just like exit the shell, you only need to type the Exit command , and you will get the following prompt when you exit successfully
[Screen is terminating]






"Reprint 2"


Linux Screen Command detailed




function Description:

telnet or ssh telnet to Linux, if the connection is not normal interruption, reconnect, the system will open a new session, unable to restore the original Session.screen command can solve the problem. The screen tool is an end-multiplexer, in essence, which means you can run multi-terminal applications using a single terminal window.

Syntax:

screen [-amrvx-ls-wipe][-d < job name >][-h < number of rows >][-r < job name >][-s][-s < job name;]

Additional notes:

Screen is a multiple Windows management program. The so-called window, refers to a full-screen text mode screen. Screen programs are often used only when Telnet is used to log on to the host computer or when using an old-fashioned terminal.

Parameters:

-A adjusts all windows to the current size of the terminal.
-D < Job name > take the specified screen job offline.
-H < number of rows > specifies the number of buffer rows in the window.
-M forces a new screen job to be established even if the screen job is currently in operation.
-R < Job name > Restore offline screen jobs.
-R first attempt to recover the offline job. If you cannot find an offline job, create a new screen job.
-s Specifies the shell to execute when a new window is created.
-S < job name > Specifies the name of the screen job.
-V Displays version information.
-X the screen job is offline before recovery.
-ls or--list displays all of the current screen jobs.
-wipe checks all current screen jobs and removes screen jobs that are not already available.

Common screen parameters:

Screen-s Yourname, a new session called Yourname
Screen-ls, List all current session
Screen-r yourname, back to yourname this session
screen-d yourname, remote detach a session
Screen-d-R Yourname End the current session and return to the session Yourname

under each screen session, all commands start with Ctrl + A (C-A).

C-a? Help, show simple instructions
C-a C-Create to open a new window
C-a N-Next, switch to next window
C-a P--Previous, previous window
C-a 0..9, switch to the first 0..9 window
CTRL + A [Space], from the Windows 0 to the video window 9
C-a c-a, switching between the two most recently used Windows
C-a x, lock the current window and unlock it with the user's password
C-a D-Detach, temporarily leave the current session, the current screen session (may contain multiple windows) to the background to execute, and will return to the status of not yet in screen, at this time in the screen session every The process (either foreground/background) that runs within a window continues to execute, even if the logout is not affected.
C-a Z, put the current session in the background, and use the Shell's FG command to go back.
C-a W-Windows, lists the windows that are turned on that have those
C-a T-time, showing the current times, and the system's load
Kill window, C-a K, forcibly closes the current window

"After the reprint, the following is my supplementary"
1. Change the window name

Usually in my use of the process, a session will correspond to several Windows (window). For example, I press CTRL + A to query the window port list, give out

1$ bash 2-$ bash 3*$ IRC

A total of 3 windows, the default is bash, the last 3 I have to change the name, called IRC, so many windows to remember is more convenient, renamed is to press CTRL + A capital A, is renamed, lowercase A is and the last time you used the window switch, this is a practical function, It's easy to remember that you have a lot of windows.
1*$ Project 2$ Bash 3-$ IRC

My 3 windows, one for the project, one for the execution of Sheel, one for my IRC, for chatting, or for testing.

2. Use the specified session name

[Email protected]:~$ Screen-dms irctest
[Email protected]:~$ screen-r
There is several suitable screens on:
4687.irctest (September 11, 2010 15:58 08 sec) (Detached)
4225.pts-0.xsty-desktop (September 11, 2010 14:45 15 sec) (Detached)
Type "screen [-d]-R [PID.] Tty.host "to resume one of them.

By default, screen uses the name of the PID.TTY.HOST, if there are too many sessions, so many of the PID may not be able to tell which is which, so it is necessary to specify a friendly name, then use the-MDS option

3. There is another article, which is IBM, and basically the above is said to have been more comprehensive.

Reproduced below http://www.ibm.com/developerworks/cn/linux/l-cn-screen/.
Linux tips: Use screen to manage your remote sessions


Tian Qiang ([email protected]), software engineer, IBM China Software Development Center



July 31, 2007





do you often need to telnet to a Linux server? Do you often have headaches for some long-running tasks? Still using the nohup? Then take a look at screen, it will give you a surprise!


Do you often need SSH or telent telnet to a Linux server? Do you often have headaches for long-running tasks such as system backups, FTP transfers, and so on. Usually we open a remote terminal window for each of these tasks because they take too long to execute. Must wait for it to finish, during this period can not shut down the window or disconnect, otherwise this task will be killed, all halfway.



Culprit: SIGHUP Signal



Let's see why shutting down the window/disconnecting will cause the running program to die.



In Linux/unix, there are several concepts:


    • Process group: A collection of one or more processes, each with a unique process group ID, which is the ID of the process leader process.
    • Session Duration: A collection of one or more process groups, with a unique session-period-first process (session leader). The ID of the session ID that is the lead process.
    • The session period can have a separate control terminal (controlling terminal). The session first process connected to the control terminal is called the control process (controlling processes). The process that is currently interacting with the terminal is called the foreground process group. The remaining process groups are called background process groups.


According to POSIX.1 definition:


    • Hang-up signal (SIGHUP) The default action is to terminate the program.
    • When the terminal interface detects a disconnected network connection, the hang-up signal is sent to the control process (session-first process).
    • If the session first process terminates, the signal is sent to the foreground process group for that session period.
    • A process exit causes an orphan process group to occur if any of the orphaned process group processes are in the stop state, sending Sighup and sigcont signals to all processes in the process group.


Therefore, when the network is disconnected or the terminal window is closed, the control process receives a SIGHUP signal exit, which causes the other process to exit during the session.



Let's look at an example. Open the two SSH terminal window and run the top command in one of them.


[email protected] root]# Top


In another terminal window, find the process ID of top 5180 and its parent process ID is 5128, which is the login shell.


[Email protected] 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


Using the Pstree command, you can see this relationship more clearly:


[Email protected] root]# pstree-h 5180|grep top|-sshd-+-sshd---bash---top


Using the PS-XJ command, you can see that the login shell (PID 5128) and top are in the same session period, the shell is the session first process, the process group Pgid is the 5128,top process group Pgid is 5180, is the foreground process group.


[Email protected] root]# ps-xj|grep 5128 5126  5128 5128  5128 pts/0 5180     S        0   0:00-bash 51285180  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, and in the other window you can see that top is also killed.


[[email protected] 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 should not affect the operation of the program. The Nohup command can do this, and if the standard output/standard error of the program is the terminal, Nohup redirects it to the Nohup.out file by default. It is important to note that the Nohup command only causes the program to ignore the sighup signal, and it needs to use tags & put it in the background to run.


Nohup <command> [argument ...] &


Although Nohup is easy to use, it is still relatively "crude", for simple commands can be dealt with, for the complex needs of human-computer interaction task is troublesome.



In fact, we can use a more powerful utility screen. A popular Linux distribution, such as Red Hat Enterprise Linux 4, usually comes with the screen utility, and if not, it can be downloaded from the official website of the GNU screen.


[Email protected] ~]# Rpm-qa|grep screenxscreensaver-4.18-5.rhel4.11screen-4.0.2-5


Start using screen



Simply put, screen is a window manager that can multiplex a physical terminal across multiple processes. Screen has the concept of session, users can create multiple screen windows in a screen session, in each of the screens window like the operation of a real telnet/ssh connection window. There are several ways to create a new window in screen:



1. Type the screen command directly at the command line


[Email protected] ~]# screen


Screens will create a full-screen window that executes the shell. You can execute any shell program, just like in the SSH window. Type exit in the window to exit the window, if this is the only window of the screen session, the screen session exits, otherwise screen automatically switches to the previous window.



2. Screen command followed by the program you are going to execute.


[Email protected] ~]# Screen VI test.c


Screen creates a single-window session that executes VI test.c, and exiting VI exits the window/session.



3. Both of these methods create a new screen session. We can also create a new window in an existing screen session. In the current screen window, type De>c-a cde>, which is the CTRL key +a, followed by the C key, screen creates a new window within the session and switches to that window.



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


[Email protected] ~]# screen VI/TMP/ABC


Then we want to quit and do something else, like go for a walk, then type de>c-a dde>,screen in the screen window to give detached hints:



temporarily interrupt a session


Came back in half an hour and found the screen session:


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


Reconnect session:


[Email protected] ~]# screen-r 16582


See what's going on, it's great, it's all there. Keep doing it.



You may notice that a special key combination c-a is used to send a command to screen. This is because the information we type on the keyboard is sent directly to the current screen window and must be issued in a different way to the screen window manager, which, by default, receives a command starting with C-a. This form of command is called key binding in screen, C-a is called command character.



All key bindings can be viewed through de>c-a?de>, and the key bindings commonly used are:



C-a? Show all key binding information C-a W display all windows list c-a c-a switch to the window that was previously displayed c-a C creates a new running shell window and switches to the window c-a n switches to the next window c-a p switches to the previous window (relative to C-a N) c-a 0..9 Switch to Window 0: 9 C-a A sends c-a to the current window C-a D temporarily disconnects the screen session C-a K kills the current window c-a [Enter copy/rollback mode





Screen common options



Using the key binding c-a? command, you can see that the default command character is C-a, and the character of the escaped c-a (literal ^a) is a:



Screen common options


Because screen sees C-a as the start of the screens command, enter c-a A If you want the c-a character to be received by the window. Screen also allows you to use the-e option to set your own command and escape characters in the following format:



-exy x is the command character, and y is the character that escapes the command character



The following command launches a screen session that specifies the command character C-t, the character of the escaped c-t is T, and the change is visible through the C-T command.


[Email protected] root]# SCREEN-E^TT


Custom command characters and escape characters


Other common command options are:



-c file uses the profile file instead of the default $home/.screenrc-d|-d [Pid.tty.host] to not open a new screen session, but instead disconnects the other running screen session-H num Specifies that the history rollback buffer size for NUM lines-list|-ls lists an existing screen session in the format pid.tty.host-d-M starts a session that is in disconnected mode-R sessionowner/[Pid.tty.host] Reconnect a disconnected session. In multi-user mode, connecting to another user screen session requires specifying Sessionowner, requiring Setuid-root permissions-s sessionname to specify a name for the session when creating a screens session-V displays the screens version information-wipe [ Match] with-list, but delete disconnected sessions





The following example shows that there are currently two screen sessions in the detached state, and you can use Screen-r <screen_pid> reconnect:


[[email protected] root]# screen –ls
There are screens on:
        8736.pts-1.tivf18       (Detached)
        8462.pts-0.tivf18       (Detached)
2 Sockets in /root/.screen.

[[email protected] root]# screen –r 8736



If for some reason one of the sessions dies (for example, by killing the session), Screen-list will show that the session is dead state. Use the Screen-wipe command to clear the session:


[[email protected] root]# kill -9 8462
[[email protected] 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.

[[email protected] root]# screen -wipe
There are screens on:
        8736.pts-1.tivf18       (Detached)
        8462.pts-0.tivf18       (Removed)
1 socket wiped out.
1 Socket in /root/.screen.

[[email protected] root]# screen -ls  
There is a screen on:
        8736.pts-1.tivf18       (Detached)
1 Socket in /root/.screen.

[[email protected] root]#


The-D–M option is an interesting pair of partners. They start a session that starts in disconnected mode. You can connect to the session when you need it later. Sometimes this is a useful feature, such as we can use it to debug background programs. A more common pairing of this option is:-dms sessionname



Start a screen session that is disconnected from the initial state:


[Email protected] tianq]# Screen-dms mygdb gdb execlp_test


To connect to the session:


[Email protected] tianq]# screen-r mygdb


Manage your remote sessions



Let's take a look at how to use screen to solve sighup problems, such as now we want FTP to transfer a large file. If you follow the old approach, SSH logs into the system, the direct FTP command begins to transfer, and then: If the network speed can also, congratulate you, do not have to wait too long, if the network is not good, honestly wait, can only transfer and then disconnect SSH connection. Let's use screen to try.



SSH login to the system and type screen at the command line.


[Email protected] root]# screen


Enter the FTP command in the Screen Shell window, log in, and start the transfer. Don't want to wait? OK, type c-a D in the window:



Manage your remote sessions


And then.. Exit SSH login? Whatever you want, just don't kill the screen session.



Isn't it convenient? Further, we can actually use screen to manage your remote session and save all your work. Do you have to open a lot of Windows every time you log on to the system, and then open the Windows repeatedly every day? Let screen to help you "save" it, you just need to open an SSH window, create the required screen window, exit c-a D "Save" your work, the next time you log in directly screen-r <screen_pid> will be OK.



It's best to give each window a name, so it's good to remember. Use C-a A to name the window. These window names can be seen using C-a W, where the names may appear differently. Using putty:



Putty


Using Telnet:



Telnet





More screen Features



Screen provides rich and powerful customization capabilities. You can specify more in the default level two profile of screen/ETC/SCREENRC and $HOME/.SCREENRC, such as setting screen options, customizing the binding key, setting the screens session self-launch window, enabling multiuser mode, customizing user access control, and more. You can also specify the screen configuration file yourself if you wish.



In the case of multi-user functions, screen is run in single-user mode by default, and you need to specify multiuser on in the configuration file to open multiuser mode via acl* (Acladd,acldel,aclchg ... ) command, you can flexibly configure other users to access your screen session. Please refer to Screen's man page for more information on the configuration file.



Resources


    • "Advanced programming in the UNIX?" Environment:second Edition "W. Richard Stevens, Stephen A. Rago provides more knowledge about Linux/unix process relationships and signals.
    • Official website of the GNU screen: http://www.gnu.org/software/screen/
    • Screen's man page provides the most detailed information: http://www.slac.stanford.edu/comp/unix/package/epics/extensions/iocConsole/screen.1.html



About the author




Tian Qiang, software engineer at the Tivoli Department of the China Software Development Center, is responsible for the maintenance and customer support work of the IBM product TMF Management Framework, and loves Linux.



[The powerful screen command in turn]linux


Related Article

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.