title: write to fifo/pipe from shell, with timeout
body: <p>I have a pair of shell programs that talk over a named pipe. The reader creates the pipe when it starts, and removes it when it exits.</p>
  
  <p>Sometimes, the writer will attempt to write to the pipe between the time that the reader stops reading and the time that it removes the pipe.</p>
  
  <pre><code>reader: while condition; do read data &lt;$PIPE; do_stuff; done
  writer: echo $data &gt;&gt;$PIPE
  reader: rm $PIPE
  </code></pre>
  
  <p>when this happens, the writer will hang forever trying to open the pipe for writing.</p>
  
  <p>Is there a <strong>clean</strong> way to give it a timeout, so that it won't stay hung until killed manually? I know I can do</p>
  
  <pre><code>#!/bin/sh
  # timed_write &lt;timeout&gt; &lt;file&gt; &lt;args&gt;
  # like "echo &lt;args&gt; &gt;&gt; &lt;file&gt;" with a timeout
  
  TIMEOUT=$1
  shift;
  FILENAME=$1
  shift;
  PID=$$
  
  (X=0; # don't do "sleep $TIMEOUT", the "kill %1" doesn't kill the sleep
   while [ "$X" -lt "$TIMEOUT" ];
   do sleep 1; X=$(expr $X + 1);
   done; kill $PID) &amp;
  
  echo "$@" &gt;&gt;$FILENAME
  kill %1
  </code></pre>
  
  <p>but this is kind of icky. Is there a shell builtin or command to do this more cleanly (without breaking out the C compiler)?</p>