1

I need to use korn shell for a script I'm writing and ran into issues managing nested child processes. The example code below demonstrates my issue. In it I create a temporary file for x seconds, then remove it so I can see if the job is still actually running. I get a list of PIDS inside and outside a backgrounded subshell "driver script"; inside, pgrep can find the child processes, but not when called outside, even though both show the correct parent PID. What do I not understand? How do I guarantee getting only the running jobs' PID (jobs -pr in bash) from outside the subshell if pgrep isn't working?

#!/bin/ksh

# create a file for x seconds and then remove it
testfunc() {
    timesec=$1
    touch "${HOME}/testfunc/testfunc_${timesec}.file"
    sleep $timesec && rm -f "${HOME}/testfunc/testfunc_${timesec}.file"
}

# subshell to manage jobs
(

    driver_script_pid="$(exec sh -c 'echo $PPID')"

    for num in 10 35 40 5; do
        testfunc $num &
        echo "child id: $!"
    done

    echo "\$\$ $$"
    echo "subshell: $driver_script_pid"
    echo "children of parent: $(pgrep -P $$)"
    echo "children of subshell: $(pgrep -P $driver_script_pid | tr "\n" " ")"

    for ids in $(jobs -p ); do
        echo "pid: $ids PPID: $(ps -p "$ids" -o ppid=) DONE"
    done

) &

driver_pid=$!

# we still have 10 sec, 35 sec, and 40 sec job still running as verified by the files 
# existing
sleep  6
echo after 6 seconds
echo "spawned driver pid: \"$driver_pid\""
echo child processes:
echo "$(pgrep -P "$driver_pid" | tr "\n" " ")"

This is the output. "spawned driver pid" matches "subshell pid" but the exact same pgrep comes up blank when run outside the backgrounded process. However, the corresponding files for the 10, 35 and 45 second jobs still exist, and are removed after the appropriate time, so I know the jobs are running.

child id: 27195
child id: 27196
child id: 27197
child id: 27199
$$ 27192
subshell: 27193
children of parent: 27193
children of subshell: 27195 27196 27197 27199 27205 
pid: 27199 PPID: 27193 DONE
pid: 27197 PPID: 27193 DONE
pid: 27196 PPID: 27193 DONE
pid: 27195 PPID: 27193 DONE
after 6 seconds
spawned driver pid: "27193"
child processes:

1 Answer 1

1

My problem had nothing to do with pgrep. The issue was that the driver script ended before the children did so all associations were de-referenced. Adding a wait to the driver fixed my issue.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .