Return the parent Screen process of a background task

Andrea Olivato
2 min readApr 8, 2019

--

Screen is one of the best companions for server admins and everyone who needs more than a simple shell.

One of the most common uses for screen, is the possibility to run a process on a remote server and leave it running on a virtual terminal that you can reconnect to. It’s great if you are on a spotty connection or waiting for a long process to complete and you want to catch the output as it gets created.

The troubles begin when you have a lot of screen processes running together on the same machine, and you can’t remember which one refers to which process.

Case in point

One of the easiest ways I’ve found to understand which screen I should reconnect to is to first look for the process I am looking for via ps and then finding the parent screen process.

To find the process you are looking for, you can simply run

ps aux | grep 'name of the process'

Once you have the PID of the process (let’s call it ${YOUR_PID}), you can use this quick snippet, which includes a regex via sed to only get the parent PID of screen and not other parent processes like bash.

pstree -s -p ${YOUR_PID} | sed -n "s/^.*screen.\{1\}\([0-9]\+\).*$/\1/p

Change ${PROCESS_PID} with the actual PID you got from ps

The output will be the PID of the parent screen process, which you can then use to reopen the same screen session with

screen -r ${SCREEN_PID}

Where ${SCREEN_PID} is the PID returned from the previous command.

--

--

Andrea Olivato
Andrea Olivato

Written by Andrea Olivato

Co-founder @Lnk.Bio — Developing stuff on the Web since 2003

No responses yet