how to capture PID for a child script

Hi,

I'm looking for a method where we can capture the PID and if possible the progress of child process especially the ones running in background.

can anyone help?

echo the PID value to a file descriptor... e.g. >&7...

thanks for your response. But i found what i was looking for.
by $! we can capture the pid for the processes ran in background.

Thanks aman for sharing the info...
If everybody does this the quality of this forum will surely improve.

My PID $
Child PID !
echo $$
startsome &
ChildPID=$!
# wait children = done the job
wait $ChildPID

PID value is good ex. to use unique tmpfile
tmpf="/var/tmp/$$.tmp"
...
rm -f "$tmpf" 2>/dev/null
or timestamp:

stamp="$( date '+%Y%m%d%H%M%S' ).$$"

If you like to do tmp remove automatic on exit, then you must catch the exit signal

tmpf="/var/tmp/$$.tmp"

cleantmp()
{
    echo "cleaning tmp files ..."
    rm -f "$tmpf" 2>/dev/null
}

#main
trap 'cleantmp'   EXIT
do_your_job
use_tmpf "$tmpf"

# on exit your tmp file is removed, if process is not stopped using signal 9 (=and I mean it).

Thanks for the information about trap command. I'm stuck in a specific situation here. I have a code snippet.

#!/bin/ksh
set -vx
PID=$$
echo "parent PID =$$"
echo "calling process1"
. $TEMP_DIR/file5
stat=$?
echo $stat
echo "calling process2"
. $TEMP_DIR/file6 &
PID2=$!
export PID2
echo "PID2= $PID2"
echo "PID1= $PID"
wait "$PID2"
status=$?
echo $status
if [ "$status" = "0"  ];then
        echo "file1 successful"
else
        echo "file1 failed"
       ## exit 1;
fi

if [ $stat -eq 0 ];then
        echo "file2 successful"
else
        echo "file2 failed"
        ##exit 1;
fi

This code is capturing the exit status of both the processes ; one in forground and other in background. Now , when i change the code to

#!/bin/ksh
set -vx
PID=$$
echo "parent PID =$$"
echo "calling process1"
. $TEMP_DIR/file5 &
PID2=$!
export PID2

echo "calling process2"
. $TEMP_DIR/file6 
status=$?
echo $status
 
echo "PID2= $PID2"
echo "PID1= $PID1"
if [ "$status" = "0"  ];then
        echo "file1 successful"
else
        echo "file1 failed"
        exit 1;
fi
wait "$PID2"
stat=$?
echo $stat
if [ $stat -eq 0 ];then
        echo "file2 successful"
else
        echo "file2 failed"
        exit 1;
fi

then the process just exists after process 2 and does not return the exit codes for either of the processes. Any idea why it is happening?

. $TEMP_DIR/file5 &
=>
$TEMP_DIR/file5 &

. $TEMP_DIR/file6
==>
$TEMP_DIR/file6

wait "$PID2"
stat=$?
= how wait worked = usually very well :slight_smile:

If you like to test you bg job end status, I think that it's not so easy in this script. Ex. child write something status to file or ....