Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spawn process on linux by using new process group id in BASH

Tags:

linux

unix

Can anyone please advise, how to spawn a new process on linux by using new process group id in BASH unix shell? Thank you so much!

like image 264
user3376989 Avatar asked Mar 04 '14 00:03

user3376989


1 Answers

To run a command, eg "emacs xxx.txt", in a new process group, from a command prompt ie interactively:

setsid emacs xxx.txt &

As described in the linked "linux command setsid", the setsid command behaviour can be surprising (and in the linux I'm using just now the manpage is not helpful at all). So...

If you want to spawn a command from within a script and have the command continue after the script exits, double the setsid:

setsid setsid emacs xxx.txt

... the rationale is:

  • when bash invokes setsid during script, setsid keeps the process group id of the bash interpreter process, and so:

    setsid emacs xxx.txt

    ... blocks (see the linked article). But it does set a new process group before running emacs

  • you can background it with '&':

    setsid emacs xxx.txt &

    ... but that leaves a race condition where the calling script might exit before the background process gets to the point where setsid changes the process group (which might kill the sub process)

  • so we want to wait for the process group change to happen; the nested setsid is guaranteed to fork because the outer setsid is not a process group leader, and will already have a new process group id set by the outer setsid

ie when we double the setsid the sequence is:

  1. bash forks child 1, leaving it in bash's process group
  2. child 1 execs setsid
  3. child 1 setsid sees it is not a group leader and so calls setsid system call (which creates new session and gives child 1 a new process group) and then execs inner setsid
  4. inner setsid sees it is a group leader, so forks child 2, child 1 exits
  5. child 2 sees it is not a group leader so calls setsid system call (which creates a new session and gives child 2 a new process group) and then execs emacs

From within a script, if you want to communicate with the command and wait for it to exit, see subprocess in the bash manpage.

like image 89
Trevor Taylor Avatar answered Sep 25 '22 22:09

Trevor Taylor