We may come across a situation when one of our process may take more time than expected which may eventually result in affecting other processes in UNIX.Suppose we have a script which is performing some task.However due to some constraint we want this task to be completed within some specific amount of time.
Say we have time slots for all our tasks and if any task is exceeding the time allowed for that task , it should be terminated.So we will see how to kill a process if it is taking more time than specified time for that process.
Following code may help in achieving exactly what we've been discussing here :
#!/bin/ksh pid=$ (sleep 12 && kill $pid) & while : do echo "This is infinite loop.However After 12 seconds it will be Terminated." sleep 5 done
In the above example, we are having an infinite loop.However thanks to sleep & kill command we can kill this process if it takes more than 12sec to execute. In variable pid, we are storing the current process id with which we are interacting.Then we are giving sleep command for 12 sec after which kill command will execute.
Notice the '&' at the end.It is very important to run this part in background so that actual script may perform the required task.After 12sec this process will be terminated.
Have you tested this method or do you know any other method to achieve the same or do you have any query regarding this code ? Feel free to share your opinion and knowledge.