Kill a Script based on the pid and sleep

I would want to run a code for 1 min and if it doesnt succeed in 1 min..I would want to exit it..I am using the following code...But the script is not going into my code part.It is waiting for 60 secs and then getting killed.
The code which is in the while loop actually takes less than 60 secs...
Could someone look into the below code

echo $$ > myprog.lck
echo sleep 60 > mytmp.sh
echo kill -9 \`cat myprog.lck\` >> mytmp.sh
sh mytmp.sh & 

while true;  

do 

  code

done 
exit 1

What shell are you using? I've tried it with both ksh93 and bash, and it works. Did you try running it with 'set -x'?

Hii..Thanks a lot...its workin now....

Also can i exit the code with a exit1 when the process is killed owing to time constraints...

Yes, there is:

#!/usr/bin/ksh

trap "exit 1" 10

( sleep 60 && kill -10 $$ ) &
WATCH=$!
SLEEP=${1:-60}

sleep $SLEEP

kill -TERM $WATCH

Exemplary output:

$ ./test.sh 5; echo $?
0
$ ./test.sh 61; echo $?
1

Note that I'm using SIGUSR1 instead of SIGKILL for the timeout, to keep the latter free for serious problems.

Heyy Thanks again...In my original code if I would want to exit the mytmp.sh when my inner code runs within the time ie I dont want the mytmp.sh to run for the entire 1 minute if my inner code gets executed in 30 secs.Any help on this front

Save the PID of the background process (it's in $!), and at the end of the script just kill it. Example (relevant part in green):

#!/usr/bin/ksh

trap "exit 1" 10

( sleep 60 && kill -10 $$ ) &
WATCH=$!
SLEEP=${1:-60}

sleep $SLEEP

kill -TERM $WATCH

Really sorry for troubling you.....

But let me get back to my script

mypid=$$
(sleep 60 && kill -TERM -$mypid) &
WATCH=$!

mycode

kill -TERM $WATCH

In the Kill statement below kill -TERM $WATCH.After executing this when I give a ps my sleep60 still seems to be running

And do we need to have a - before $WATCH

---------- Post updated at 11:27 PM ---------- Previous update was at 08:44 AM ----------

I am still stuck up with the issue..Any help!!!!