名前つきパイプを使って他のプロセスと通信する

#!/bin/sh
#np_server.sh - サーバプロセス

PIPE="/tmp/np_server.pipe"
SVER=1

cleanup(){
    echo "Cleanup" >&2
    [ -p $PIPE ] && rm $PIPE
    exit
}

if [ -e $PIPE ]; then
    echo "Named pipe $PIPE already exist."
    echo "If it is sure that server in not running,"
    echo "remove if manually and restart server."
    exit 1
fi

trap cleanup INT TERM
#名前つきパイプを作成する
mkfifo -m 600 $PIPE

#クライアントから送られてくるコマンドを読み込む
while true; do
    read command < $PIPE
    set -- $command 
    case $1 in
        #単語数を数える
        WCNT) echo 0 `expr $# - 1` >> $PIPE
              ;;
        #サーバのバージョンを返す
        SVER) echo 0 $SVER > $PIPE
              ;;
        *   ) echo 1 "Unknown command" >> $PIPE
    esac
done
#!/bin/sh
#np_client.sh - クライアントプロセス

PIPE="/tmp/np_server.pipe"

if [ ! -e $PIPE ]; then
    echo "np_server.sh is notrunning."
    exit 1
fi

#サーバと接続しバージョンを確認
echo "SVER" >> $PIPE
read code ver < $PIPE
echo "Connected to np_server.sh (ver $ver)"

#標準入力から読み込んだデータをサーバに送信し単語数を得る
wcnt=0
while read line; do
    echo WCNT "$line" >> $PIPE
    read code c < $PIPE
    wcnt=`expr $wcnt + $c`
done

echo $wcnt
$ ./np_client.sh < np_client.sh 
Connected to np_server.sh (ver 1)
54