title: Terminating background commands vs subshells
body: <p>I encountered a behavior I do not understand about how a parent bash script can terminate the execution of its child processes when those child processes are executed in background.</p>
  <p>Here are very easy bash scripts to illustrate my mis-understanding.</p>
  <p><code>child.sh</code> which only waits.</p>
  <pre class="lang-sh prettyprint-override"><code>#!/bin/bash
  
  while :
  do
      sleep 10000
  done
  </code></pre>
  <p><strong>version 1</strong> : <code>parent.sh</code> with child scripts directly executed in background</p>
  <pre class="lang-sh prettyprint-override"><code>#!/bin/bash
  
  ./child.sh &amp;
  ./child.sh &amp;
  wait
  </code></pre>
  <p>If we execute <code>parent.sh</code> and enter <code>Ctrl+C</code> for the <code>parent.sh</code> script to terminate then the 2 child processes are still running after.</p>
  <pre class="lang-sh prettyprint-override"><code>$ ./parent.sh
  ^C
  $ ps aux | grep child.sh
  946702 pts/5    00:00:00 child.sh
  946703 pts/5    00:00:00 child.sh
  </code></pre>
  <p><strong>version 2</strong> : <code>parent-sub-shells.sh</code> with child scripts executed in sub-shells and then in background</p>
  <pre class="lang-sh prettyprint-override"><code>#!/bin/bash
  
  (./child.sh) &amp;
  (./child.sh) &amp;
  wait
  </code></pre>
  <p>If we execute  <code>parent-sub-shells.sh</code> and enter <code>Ctrl+C</code> for the <code>parent.sh</code> script to terminate the 2 child processes are correctly killed.</p>
  <pre class="lang-sh prettyprint-override"><code>$ ./parent-sub-shells.sh
  ^C
  $ ps | grep child.sh
  </code></pre>
  <p>Why the behavior is different between the 2 versions ? Especially concerning the fact one version is killing the child processes and not the other.</p>
  <p>Thanks for your help.</p>
  <p>Baptiste</p>