Search code examples
gnu-screen

How to keep the window opened even after the command returned or is killed?


I open a detached screen and run some commands in new windows:

screen -dm -S test
screen -S test -X screen -t htop htop
screen -S test -X screen -t top top
screen -S test -X screen -top dmesg dmesg -w

and also try

screen -dm -S test
screen -S test -x -X screen htop
screen -S test -x -X screen top
screen -S test -x -X screen dmesg -w

That works well. When I reattach the screen screen -r test and I kill the running app with ctrl+c, the window is closed at the same time.

When creating new window manually via ctrl+a+c and I run top/htop/whatever inside, if I kill the app, the window stays and I can run new command.

Why? How can I have the same behavior? I want to be able to kill and run the command again in the same window.


Solution

  • Answer

    You need to let screen know that you want a shell running in the new window with a command running in that shell. The simplest way (that I know) to accomplish this is to create the window separately from running the command in it:

    screen -S session_name -X screen -t tab_name
    screen -S session_name -p tab_name -X stuff "command_to_run \r"
    

    Example:

    screen -S test -X screen -t htop_tab
    screen -S test -p htop_tab -X stuff "htop\r"
    

    Notes:

    • The \r is there to simulate hitting the return key.
    • stuff will let you interact with any running process in that window

    Explanation

    The difference between the manual method and the command you are using is:

    • When you create a new window manually, you are creating a window with an interactive shell running in it, and then you type a command in the shell to start a program. When you kill that program, it goes back to the shell and you can do whatever you want.
    • Your command, on the other hand, is instructing screen to create a new window with the provided command running in it (i.e. don't run a shell), so when you kill it, there is no process running in the window and it closes

    Relevant excerpts from the screen man page:

    In the Default Key Bindings section:

      C-a c,             (screen)          Create a new window with
      C-a C-c                              a  shell  and  switch to
                                           that window.
    

    In the description of the internal screen command:

    If a command is specified after "screen", this command (with the given arguments) is started in the window; otherwise, a shell is created.