Bash: Getting PID of daemonized screen session
This show the pid for a screen named nameofscreen
:
$ screen -ls
There are screens on:
19898.otherscreen (07/03/2012 05:50:45 PM) (Detached)
19841.nameofscreen (07/03/2012 05:50:23 PM) (Detached)
2 Sockets in /var/run/screen/S-sarnold.
$ screen -ls | awk '/\.nameofscreen\t/ {print strtonum($1)}'
19841
$
you can use:
screen -DmS nameofscreen
which does not fork a daemon process allowing you to know the pid.
Parsing the output of screen -ls can be unreliable if two screen sessions have been started with the same name. Another approach is to not let the screen session fork a process and put it in the background yourself:
For example with an existing initial screen session:
fess@hostname-1065% screen -ls
There is a screen on:
19180.nameofscreen (01/15/2013 10:11:02 AM) (Detached)
create a screen using -D -m instead of -d -m which does not fork a new process. Put it in the background and get it's pid. (Using posix shell semantics)
fess@hostname-1066% screen -DmS nameofscreen &
[3] 19431
fess@hostname-1067% pid=$!
Now there are two screens both have the same name:
fess@hostname-1068% screen -ls
There are screens on:
19431.nameofscreen (01/15/2013 10:53:31 AM) (Detached)
19180.nameofscreen (01/15/2013 10:11:02 AM) (Detached)
but we know the difference:
fess@hostname-1069% echo $pid
19431
and we can accurately ask it to quit:
fess@hostname-1070% screen -S $pid.nameofscreen -X quit
[3] - done screen -DmS nameofscreen
now there's just the original one again:
fess@hostname-1071% screen -ls
There is a screen on:
19180.nameofscreen (01/15/2013 10:11:02 AM) (Detached)