If I start a GNU screen session as a daemon, how would I retrieve its PID programmatically? I don't know how consistent the output of screen -ls
is, so I'd like to know how to do this with one of bash's constants, $$
, $!
or a better alternative.
I am starting the screen with screen -dmS screenname
.
How would I get the PID of a screen right before or immediately after starting the screen session?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With