#!/bin/bash
# exemple de lecteurs/ecrivains
maxR=2
maxW=2
maxTime=2
rCountFileName="nbL.txt"
trap "rm ${rCountFileName}" 0 1 3 15

echo 0 > "${rCountFileName}"
incrL () {
    read nbL < "${rCountFileName}"
    nbL=`expr "${nbL}" \+ 1`
    echo "${nbL}" > "${rCountFileName}"
}
decrL () {
    read nbL < "${rCountFileName}"
    nbL=`expr "${nbL}" \- 1`
    echo "${nbL}" > "${rCountFileName}"
}

mkfifo pipe
for (( i=0 ; i - ${maxR} ; i++ ))
do
    (
	echo -n "${BASHPID} " > pipe
	sleep 1
	incrL
	for  (( j=0 ; j - ${maxTime} ; j++ ))
	do
	    echo `date +"%H:%M:%S"` " je lis (r$i)"
	    sleep 1
	done
	decrL
    )&
done
for (( i=0 ; i - ${maxW} ; i++ ))
do
    (
	echo -n "${BASHPID} " > pipe
	sleep 1
	for  (( j=0 ; j - ${maxTime} ; j++ ))
	do
	    echo `date +"%H:%M:%S"` " j'ecris (w$i)"
	    sleep 1
	done
    )&
done
sleep 1
read pids < pipe
rm pipe

wait ${pids}
exit # nettoyage dans le trap
rm "${rCountFileName}"
