title: Varying behavior when using named pipe with background process
body: <p>I'm having a hard time understanding named pipes. I have the following script:</p>
  
  <pre><code>#!/bin/bash
  
  function a_or_b {
     echo 'func begins'
  
     while true; do
        echo 'loop begins'
  
        read -s -n 1; echo $?
        case $REPLY in
           'a') return 0 ;;
           'b') return 1 ;;
        esac
     done
  
     echo 'func ends'
  }
  
  mkfifo pipe
  a_or_b &lt;pipe &amp;
  </code></pre>
  
  <p>Now what I was expecting this script to do is:</p>
  
  <ol>
  <li>enter <code>a_or_b</code> and therefore print <code>func begin</code></li>
  <li>enter the loop and therefore print <code>loop begins</code></li>
  <li>read an <em>EOF</em> from <em>stdin</em>, and therefore from <code>pipe</code>(as I have not written anything to <code>pipe</code>) and therefore print <code>1</code> as <code>$?</code> </li>
  <li>not match on either case-clause and therefore go back to step 2</li>
  </ol>
  
  <p>When running this script though I get no output and my terminal simply prints its next prompt.</p>
  
  <hr>
  
  <p>If I redirect an <em>echo</em> into <code>pipe</code> <strong>before</strong> calling <code>a_or_b</code>:</p>
  
  <pre><code>...
  
  mkfifo pipe
  echo 'x' &gt; pipe
  a_or_b &lt;pipe &amp;
  </code></pre>
  
  <p>... the script doesn't stop running and I can keep entering characters (including <code>a</code> and 'b') in the terminal to no effect. So I have to end the script using <em>^C</em>.</p>
  
  <hr>
  
  <p>If I redirect an <em>echo</em> into <code>pipe</code> <strong>after</strong> calling <code>a_or_b</code>:</p>
  
  <pre><code>...
  
  mkfifo pipe
  a_or_b &lt;pipe &amp;
  echo 'x' &gt; pipe
  </code></pre>
  
  <p>... I get the following output:</p>
  
  <pre><code>func begins
  loop begins
  0
  loop begins
  0
  loop begins
  1
  loop begins
  1
  loop begins
  1
  
  </code></pre>
  
  <p>This is basically the behavior I expected from not <em>echoing</em> anything to <code>pipe</code>. The function begins, goes into the loop, reads the <code>x</code> and <code>\n</code> characters from the <code>echo</code> (corresponding to the two <code>0</code>s in the output) and then keeps looping forever while failing to read any characters. And if I <em>echo</em> <code>a</code> or <code>b</code> into the pipe, the function ends.</p>
  
  <hr>
  
  <p>What is causing all of these different behaviors?</p>