timeout.sh 873 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#
# LECA Bash library
#
# The LECA bash library provides a set of function used for helping
# development of bash script mainly to write job script on the luke
# cluster
#
# The files from the LECA Bash library must be sourced from your main script
#

include logging
logdebug "Load timeout package"


function timeoutcmd() {
  local seconde=$1
  shift
  
  $* &
  
  local mainpid=$!
  sleep $seconde &
  local sleeppid=$!

  local nproc=$(ps $mainpid $sleeppid | tail -n +2 | wc -l)

  while (( nproc > 1 )) ; do
    sleep 1
    nproc=$(ps $mainpid $sleeppid | tail -n +2 | wc -l)
  done

  local timealive=$(ps $sleeppid | tail -n +2 | wc -l)
  
  if (( timealive > 0 )) ; then
    kill -9 $sleeppid 
  else
  	if (( $(ps $mainpid | tail -n +2 | wc -l) > 0 )) ; then
  	 	kill -9 $mainpid
39 40
    	logwarning "Timeout after ${seconde}s on command : $*"
		return 1
41 42 43
	fi
  fi
}