Shell – How to periodically check if STDIN is open

file-descriptorsshell

Some programs will exit when their STDIN is closed. Those that do this work nicely with Erlang/Elixir supervision via "ports".

For those that don't, the Elixir docs suggest this wrapper script:

#!/bin/bash
# wrapper.sh
"$@" &
pid=$!
while read line ; do
  :
done
kill -KILL $pid

This allows calling wrapper.sh my_script arg1 arg2. wrapper.sh starts and backgrounds the specified program, and when wrapper.sh's STDIN is closed, its blocking read finishes and it terminates the backgrounded process.

This approach has a downside, however; if the backgrounded process terminates for some other reason, wrapper.sh doesn't notice, and therefore neither does Erlang/Elixir.

I'd like to modify this script to do the following:

In a loop:

  • If STDIN is closed, kill $pid
  • If $pid is dead, exit
  • Otherwise, sleep briefly

Can anyone suggest a way to do this?

Best Answer

You can check if $pid is dead like so:

while kill -0 $pid >/dev/null; do
    # $pid is still alive
done

# $pid is dead or you lack permissions to send signals to it
Related Question