Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Waiting for a process without using pid



On 09/16/2010 07:56 PM, Bart Schaefer wrote:
On Sep 16,  4:09pm, Anonymous bin ich wrote:
}
} I am trying to write a 'timeout' script, which will take 2 commands
} and exit after whichever one exits first. Is there a way to do it
} without using pid or polling?

Sure.

     job1&
     job2&
     coproc read
     trap "trap - CHLD ; kill $! " CHLD  # Here $! is PID of coprocess
     read -p

This sets up a coprocess child that's blocking on the parent, and then
makes the parent block on the child, creating a deadlock.  The trap
breaks the deadlock by killing the coprocess, at which point the
parent wakes up.

You might need to prefix job1 and job2 with "sleep 2 ;" to prevent a
race condition where one of the jobs exits before the trap is ready.

But I see that job2 is still running at the end, just the script having this code forks at then kills both its instances.

~ % cat a.sh
#!/usr/bin/zsh

./b.sh 10&
echo $!
./b.sh 20&
echo $!
coproc read
trap "trap - CHLD ; echo gonna kill $!; kill $!; echo killed $! " CHLD # Here $! is PID of coprocess
read -p
echo "finishing script"
exit 0

~ % cat b.sh
#!/usr/bin/zsh
echo start $1 in $$
sleep $1
echo stop $1 in $$

~ % ./a.sh
30213
30214
start 10 in 30213
start 20 in 30214
stop 10 in 30213
gonna kill 30215
killed 30215
finishing script
~ % ps
  PID TTY          TIME CMD
30053 pts/2    00:00:00 zsh
30214 pts/2    00:00:00 b.sh
30217 pts/2    00:00:00 sleep
30218 pts/2    00:00:00 ps
~ % stop 20 in 30214
                                                23:50

~ % ps
  PID TTY          TIME CMD
30053 pts/2    00:00:00 zsh
30219 pts/2    00:00:00 ps
~ %



Messages sorted by: Reverse Date, Date, Thread, Author