title: Implementing infinite wait in shell scripting
body: <p>This may sound trivial, but I'm pretty sure this question hasn't been asked, or at least I can't find it.</p>
  
  <p>I'm looking for a way to construct an <strong>infinite wait</strong> (not necessarily a loop) with shell scripting so that it <strong>waits forever and can be killed</strong> (or technically, to receive a <code>SIGTERM</code>). The following are known possible constructs and arguments against them:</p>
  
  <ol>
  <li><code>while true; do sleep 1; done</code> This almost gets it, but since <code>sleep</code> is an external command, when I send a <code>SIGTERM</code> to the running script, it has to wait for the <code>sleep</code> to finish first and then process the signal. Change <code>sleep 1</code> to something like <code>sleep 10</code> and the lag will be obvious. Also the solution wakes up the CPU every 1 second, which is not ideal.</li>
  <li><code>while true; do read; done</code> This is perfect when <code>stdin</code> is tty. <code>read</code> is a shell builtin and <code>SIGTERM</code> arrives at the script instantly. But, when <code>stdin</code> is <code>/dev/null</code>, the script eats up all the CPU by helplessly running <code>read</code> forever on <code>/dev/null</code>.</li>
  </ol>
  
  <p>Thus a <strong>shell builtin construct</strong> that waits forever is required. Skimming through <code>man dash</code> I didn't find such one - the only blocking builtins are <code>read</code> and <code>wait</code>, and I don't have idea how I can construct an ideal one using <code>wait</code>.</p>
  
  <p>The answer should be applicable to POSIX shell (effectively <code>dash</code>), or less preferably, Bash.</p>
  
  <p><strong>Additional notes.</strong></p>
  
  <p>The situation where the first example doesn't work perfectly is more complex than I thought. With the following shell script:</p>
  
  <pre><code>#!/bin/sh
  echo $$
  while true; do
      sleep 100
  done
  </code></pre>
  
  <p>if you kill it at another tty, it terminates immediately. The funny thing begins when you attempt to do trapping. With this script:</p>
  
  <pre><code>#!/bin/sh
  at_term() {
      echo 'Terminated.'
      exit 0
  }
  trap at_term TERM
  echo $$
  while true; do
      sleep 20
  done
  </code></pre>
  
  <p>What happens is exactly described in example 1. This happens with bash, dash and zsh. And it's under this condition that I'm seeking a "perfect" infinite look construct.</p>