#!/bin/bash

lockfile="/.nslock"
SUCCESS=0
FAIL=1
otherpid=
startparent()
{
        rm -f $lockfile
        echo $$ >| ${lockfile}parent
        while [ 1 ]
        do
                otherpid="$(cat ${lockfile}child 2> /dev/null)"
                if [ -n "$otherpid" -a -d /proc/$otherpid ]
                then
                        return
                fi
        done
}

startchild()
{
        rm -f $lockfile
        echo $$ >| ${lockfile}child
        while [ 1 ]
        do
                otherpid="$(cat ${lockfile}parent 2> /dev/null)"
                if [ -n "$otherpid" -a -d /proc/$otherpid ]
                then
                        return
                fi
        done
}

iamgoingahead()
{
        while [ 1 ]
        do
                if [ ! -d /proc/$otherpid ]
                then
                        return $FAIL
                fi
                str=`cat $lockfile 2> /dev/null`
                pid=$(echo $str | awk '{print $1}')
                error=$(echo $str | awk '{print $2}')
                if [ "$pid" == "$$" ]
                then
                        return $error
                fi
                sleep 1
        done
}

goahead()
{
        set -x
        ret=$SUCCESS
        if [ -n "$1" ]
        then
                ret=$1
        fi
        echo "$otherpid $ret" >| $lockfile
        set +x
}