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

Re: Waiting for a process without using pid



On 09/20/2010 10:20 PM, PJ Weisberg wrote:
On Mon, Sep 20, 2010 at 7:55 AM, Bart Schaefer
<schaefer@xxxxxxxxxxxxxxxx>  wrote:

Perhaps I was trying to make my solution too general; i.e., I didn't
want to care how many children were started or whether their PIDs had
been remembered.  But if you always have exactly two children, why not
this?

    coproc read -E
    trap "print -p" CHLD

    ./child.sh&
    pid1=$!
    ./child.sh&
    pid2=$!

    read -p
    kill $pid1>&/dev/null
    kill $pid2>&/dev/null

You *can* rewrite that to not care how many children there are.

for thing in $stuff; do
     ./child.sh $thing
     set -A pids $pids $!
done

for child in $pids; do
     kill $child>&/dev/null
done
Ok, I have modified child.sh as following:

#!/bin/sh
if [ $# -gt 0 ]; then
    gotsig=0
    deadchild=0
    trap "exitfunc" INT HUP TERM
    trap "exitdeadchildfunc" CHLD
    exitfunc () {
        echo $$: Got sig...
        gotsig=1
    }
    exitdeadchildfunc () {
        echo $$: SIG is CHLD...
        deadchild=1
    }
    echo $$: Sleeping for $1 seconds
    sleep $1 &
    wait
    if [ $gotsig -ne 0 ]; then
        if [ $deadchild -ne 0 ]; then
            echo $$: sleep in for $1 seconds already stopped (no $!)
        else
            echo $$: Stopping sleep for $1 seconds in $!
            kill $!
        fi
    else
        echo $$: Slept for $1 seconds
    fi
else
    echo No args
    exit 1;
fi


So, two normal cases are:

% ./parent.sh
6680: Launching 2 child processes
6682: Sleeping for 1 seconds
6683: Sleeping for 5 seconds
6682: SIG is CHLD...
6682: Slept for 1 seconds
6680: Waking coprocess
Woken
Finishing 6680
6680: got HUP
6680: Waking coprocess
6683: Got sig...
6683: Stopping sleep in 6685 for 5 seconds
% ./parent.sh
6686: Launching 2 child processes
6688: Sleeping for 1 seconds
6689: Sleeping for 5 seconds
6688: SIG is CHLD...
6688: Slept for 1 seconds
6686: Waking coprocess
Woken
Finishing 6686
6686: got HUP
6686: Waking coprocess
6689: Got sig...
6689: SIG is CHLD...
6689: sleep in 6691 for 5 seconds already stopped
%

And one abnormal case is:
% ./parent.sh
6620: Launching 2 child processes
6622: Sleeping for 1 seconds
6623: Sleeping for 5 seconds
6622: SIG is CHLD...
6622: Slept for 1 seconds
6620: Waking coprocess
6620: Waking coprocess
% 6623: SIG is CHLD...
6623: Slept for 5 seconds

%

Now what is happening? Also, anyway do debug it (set -x isn't very helpful since all processes write simultaneously)



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