Operating System - HP-UX
1833059 Members
2596 Online
110049 Solutions
New Discussion

Specifying command timeout

 
SOLVED
Go to solution
Neeraj_7
Frequent Advisor

Specifying command timeout

I m running a command in a script which takes very long times to execute in certain cases. I want that if the command execution takes more than 15 sec, it exits and continues with the next command in the script. Can u all plz suggest me a way out.
4 REPLIES 4
Muthukumar_5
Honored Contributor

Re: Specifying command timeout


we have to the function's in shell in background mode so that main process will be having control on that.

Example:
#!/usr/bin/sh
set -x

fun1()
{
hostname
sleep 20
uname -a

# Normal exit
exit 0
}

sec()
{
ifconfig lan0
echo ok

# Exit
exit 0
}

# Main script

fun1 &
pid=$!

sleep 10

if [[ $(ps -ef | grep -v grep | grep -qw "$pid") -eq 0 ]]
then

kill -9 $pid

fi

# As normal execution; if
# Start second function
sec &
newpid=$!

# check here.

# Script exit
exit 0


fun1 will be expected for 10 minutes. If it is not giving the results then try to make the process stop.

If you want to store the results and error's in a file of the function execution then,

execute as,

fun1 1>/tmp/testlog.out 2>/tmp/testerror.err

HTH.
- Muthu
Easy to suggest when don't know about the problem!
Sridhar Bhaskarla
Honored Contributor
Solution

Re: Specifying command timeout

Hi Neeraj,

This example script should give you the information you need. Basically you will put the command in the background and check it for every "n" seconds. Kill it after it reaches your limit.

LIMIT=15
COUNT=1
CHECK=2
sleep 20 > /dev/null 2>&1 &
PID=$! #<< PID of the background process
while [ $COUNT -le $LIMIT ]
do
if $(UNIX95= ps -p $PID > /dev/null 2>&1)
then
echo "$PID is still running"
sleep $CHECK
(( COUNT = $COUNT + 1 ))
else
(( COUNT = $LIMIT + 100 ))
kill -0 $PID
break
fi
done

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
RAC_1
Honored Contributor

Re: Specifying command timeout

15 seconds of what??
Elapsed time??
CPU mode time???

Can be done as follows.

start process
speep 15
check if it is there??, if yes kill it.
if not continue

You can use kill -0 "pid" to check if process is active or not.
kill -0 1234
echo $? -->> if zero it is active, else not.

Anil

Anil
There is no substitute to HARDWORK
Neeraj_7
Frequent Advisor

Re: Specifying command timeout

The solution by Sridhar Bhaskarla helped a lot.