×
Community Blog Multiplexing and Making Terminal Sessions Persistent with tmux

Multiplexing and Making Terminal Sessions Persistent with tmux

In this tutorial, we will learn how to use tmux to run multiple text-based programs and shell sessions to manage your ECS instances.

By Alexandru Andrei, Alibaba Cloud Tech Share Author. Tech Share is Alibaba Cloud's incentive program to encourage the sharing of technical knowledge and best practices within the cloud community.

As you manage Alibaba Cloud Elastic Compute Service (ECS) instances, you will often find yourself working at the command line in so-called pseudo-terminal sessions. Typically, you would connect to your server with an SSH client like PuTTY and after logging in you are dropped into a shell like Bash where you can enter commands and interact with the operating system. For most purposes, this simple setup suffices. However, in certain scenarios, you may need, or at least benefit, from expanding the capabilities of such a session with a terminal multiplexer like tmux. Just like the operating system running on your phone or computer can execute and display, side by side, multiple applications on its graphical user interface, so can tmux do with text-based programs and shell sessions. But practical examples are easier to understand than theory alone so let's explore a few use cases:

  1. You want to see how your web server responds to stress tests. You need to log in through SSH two times: in a window you open a resource monitoring application like "htop" and in another window you enter commands to perform the stress test. With a terminal multiplexer you can avoid multiple logins, launching as many shell sessions as you need, in a single SSH session. Here's a picture of three Bash shells hosted in tmux:

    1


Although it's called a multiplexer, tmux can do many other interesting things besides multiplexing terminals. The ability to keep a session running, even if the user disconnects from it, makes it very useful in some scenarios. Furthermore, you can also reattach to such sessions, which lets you see previous output you may have missed in the terminal and reestablishes the ability to interact with the input of programs running there. Example use cases:
  1. You need to compile a large project. It is estimated that this job will require at least 8 hours. If your SSH connection drops unexpectedly after say, 4 hours, the job will be interrupted and you may have to restart from scratch. If you run the compile in a tmux session, it doesn't get interrupted even if your connection drops or you simply need to log out from the server. You can later come back, reattach to the session and see how the compile job has progressed during your absence.
  2. You are running a game server which doesn't have a ready-made daemon script to put the process in the background. Instead, this program runs in the foreground and if you would quit your SSH session, it would be closed. You do have options to daemonize a process yourself, either through Bash commands or by writing systemd scripts, but, in this case, it's unfeasible because the game server utility also provides its own command line. Losing the terminal session would leave you without the ability to further interact with the program's input and change game settings while it's running. With tmux, you can detach from the terminal, let the game utility run, and when you log back in you can re-attach to the terminal and input commands to kick or ban users, change maps and manage the game hosted on your instance.

Although obviously not limited to these use-cases, we can see that we will generally want tmux when we:

  1. Have to run multiple terminal sessions in a single SSH session.
  2. Run jobs that take a very long time to complete and we can't risk getting disconnected and losing progress.
  3. Have a daemon type process that runs permanently on the instance and we need the ability to detach and reattach, as needed, to the terminal hosting the application to reestablish connectivity to the utility's text-based input/output interface.

Now let's learn how to use tmux.

Install tmux

On Debian or Ubuntu run:

apt update && apt install tmux

On CentOS:

yum install tmux

And on OpenSUSE:

zypper refresh && zypper install tmux

Attach and Detach from tmux Sessions

Let's start tmux:

tmux

Run the following command to start a simple countdown, from 600 to 1 (10*60 seconds = 10 minutes):

for i in `seq 1 $((10*60)) | tac`; do clear; echo $i; sleep 1; done; echo "Finished!"

Now you can test what would happen if your SSH connection would end abruptly. For example, if you're running PuTTY, force-close the window. Afterward, log back in to your server and enter the following command:

tmux attach

This reattaches you to the session and you will see that the countdown continued even while you were disconnected. If the need ever arises, you can also manually detach from a tmux session by pressing CTRL+B, then releasing the CTRL key and afterwards pressing D. CTRL+B is the default so-called prefix key. This combination signals that the next key/keys pressed should be caught and interpreted by tmux. Reattach to the previous session if you have detached:

tmux attach

Manage tmux Windows

We've seen how easy it is to keep processes running in the background and reattach to their input and output even if we lose connectivity. Now let's explore the multiplexing part. Let's say one process will take a long time to complete. This is represented by the 600 second counter that should still be running. But we want to do other things on the server during this time. To open another window in tmux press CTRL+B (now release CTRL) and then press C. In the bottom status bar you will see we have two windows now:

2

"0:" and "1:" represents the index number of the window. After this number, the name of the process currently running in the window is displayed. The "*" symbol is added to the window which is currently displayed (active). Now we can do other work while the process in window 0 progresses. To switch to the previous window press CTRL+B followed by P. Press CTRL+C if the countdown is still running to stop it. To close a window, simply stop all the processes running there and exit the bash session with:

exit

tmux Panes

Windows are useful when you need to focus and multitask in full screen, but sometimes you will want to simultaneously see the output of multiple tasks/processes. In this case, you can split a window in panes. To split vertically, press CTRL+B and then % (on most keyboards this will mean actually pressing SHIFT+5 since that's where we find the percent sign; however keyboards that are not in the US layout will require a different combination of keys). The result should look like this:

3

To split a window horizontally, press CTRL+B followed by " (quotation mark). If we are already in an active pane, this will sub-split it. In our case, the result should look like this:

4

To change the active pane you want to work in press CTRL+B then O. This will switch to the next one. A list of useful keyboard shortcuts will be provided at the end of this tutorial.

tmux Command Mode

We currently have a window with three panes. To create another workspace, you can launch a new window and then also split that into panes. Furthermore, you can even launch a new tmux session, which can consist of an entirely different collection of windows and panes. You can then switch between these sessions as required. We've seen how to use keyboard shortcuts, now let's learn a new way we can interact with tmux. You can enter command mode interaction by pressing CTRL+B followed by : the colon sign. The input cursor will move to the bottom status bar, where you can type the name of the tmux command you want to execute. Type this to start a new session:

new-session

5

Press ENTER to execute the command. A new session will initialize with one window and one pane. To switch to the previous session, press CTRL+B and then ( the open parenthesis sign.

Here's another tmux command you might find useful. Press CTRL+B then : and enter the command set -g mouse on. This will enable mouse interaction. Now you can switch to another active pane by simply clicking on the respective pane box. By clicking and dragging the line separating panes, you can resize them.

You can add such options to a configuration file in your home directory. This would apply them automatically each time you launch tmux.

You can create this file now and add the previous option with:

echo 'set -g mouse on' >> ~/.tmux.conf

If your user's name on your Alibaba ECS instance is "johnsmith" you will find the file in this location: /home/johnsmith/.tmux.conf.

List of tmux Shortcut Keys

To manage windows, after pressing the prefix key (by default, CTRL+B), press:

  1. c -- Create a new window.
  2. n -- Switch to the next window.
  3. p -- Switch to the previous window.
  4. 0 to 9 -- Select window by its index number.
  5. w -- Display an interactive menu with all available windows. You can navigate this menu with the arrow keys and switch to the desired window.
  6. & -- Kill current window; forcibly terminates all processes running in all the panes currently displayed.

To manage panes, after pressing the prefix key (by default, CTRL+B), press:

  1. % -- Split in two vertical panes.
  2. " -- Split in two horizontal panes.
  3. o -- Switch to the next pane available in the current window.
  4. { or } -- Swaps/moves the currently selected pane to the position of the next pane, or the previous one.
  5. ARROW KEY -- Any of the four arrow keys (left, right, up, down), will select the pane adjacent to the respective direction, relative to the currently active pane.
  6. CTRL+ARROW KEY -- Resize the currently active pane in the direction of the arrow key. Pressing the same arrow key multiple times (without releasing CTRL), resizes the pane further. In case you're having problems with this in PuTTY, read: https://superuser.com/questions/1165287/ctrl-arrow-keys-for-tmux-not-working-in-putty
  7. x -- Kill (force close) all processes running in current pane and close it.
  8. z -- Zoom into pane (maximize). Press combination of keys again (CTRL+B, z) to zoom out.

To manage sessions, after pressing the prefix key (by default, CTRL+B), press:

  1. ( or ) -- Switch to the previous or next session.
  2. s -- Display an interactive menu with available sessions. You can navigate the menu with your arrow keys and press enter to switch to the desired session.
  3. $ -- Rename the currently active session.

To scroll up and see previous terminal output, press CTRL+B followed by PAGE UP. PAGE UP, PAGE DOWN and arrow keys can be used to navigate through the output. Press q when you want to quit this mode and return to the command prompt/current output.

This summarizes the basics and most widely used options of tmux. However, the utility is very flexible, customizable and includes hundreds of other functions. If you want to read more about it, you can either consult your distribution's manual page with a command like man tmux, read the manual online, if you find an HTML page is easier to navigate (https://manpages.debian.org/stretch/tmux/tmux.1.en.html) or even read a book on the subject: https://leanpub.com/the-tao-of-tmux/read.

0 0 0
Share on

Alibaba Clouder

1,440 posts | 229 followers

You may also like

Comments

Alibaba Clouder

1,440 posts | 229 followers

Related Products

  • ECS(Elastic Compute Service)

    An online computing service that offers elastic and secure virtual cloud servers to cater all your cloud hosting needs.

    Learn More
  • Server Load Balancer(SLB)

    Alibaba Cloud Server Load Balancer is built to cope with high volume traffic and each year in November is put to the test during Alibaba’s annual Global Shopping Festival. Alibaba relies on Server Load Balancer to provide uninterrupted service during the festival by switching requests between data centers and transferring transactions to the most available server.

    Learn More
  • CloudMonitor

    Automate performance monitoring of all your web resources and applications in real-time

    Learn More