Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Getting PID of daemonized screen session

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?

like image 961
hexacyanide Avatar asked Jul 03 '12 23:07

hexacyanide


1 Answers

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)
like image 153
fess . Avatar answered Oct 24 '22 20:10

fess .