title: linux command setsid
body: <p>I am trying to write a wrapper which will execute a script as a session leader.
  I am confused by the behaviour of the linux command <code>setsid</code>. Consider this script, called <code>test.sh</code>:</p>
  
  <pre><code>#!/bin/bash
  SID=$(ps -p $$ --no-headers -o sid)
  if [ $# -ge 1 -a $$ -ne $SID ] ; then
    setsid bash test.sh
    echo pid=$$ ppid=$PPID sid=$SID parent
  else
    sleep 2
    echo pid=$$ ppid=$PPID sid=$SID child
    sleep 2
  fi
  </code></pre>
  
  <p>The output differs depending on whether it is executed or sourced:</p>
  
  <pre><code>$ bash
  $ SID=$(ps -p $$ --no-headers -o sid)
  $ echo pid=$$ ppid=$PPID sid=$SID
  pid=9213 ppid=9104 sid= 9104
  $ ./test.sh 1 ; sleep 5
  pid=9326 ppid=9324 sid= 9326 child
  pid=9324 ppid=9213 sid= 9104 parent
  $ . ./test.sh 1 ; sleep 5
  pid=9213 ppid=9104 sid= 9104 parent
  pid=9336 ppid=1 sid= 9336 child
  $ echo $BASH_VERSION 
  4.2.8(1)-release
  $ exit
  exit
  </code></pre>
  
  <p>So, it seems to me that <code>setsid</code> returns immediately when the script is sourced, but it waits for its child when the script is executed.
  Why would the presence of a controlling tty have anything to do with <code>setsid</code>? Thanks!</p>
  
  <p>Edit: For clarification I added pid/ppid/sid reporting to all relevant commands.</p>