0

The following posts teach us how to run a process for some time: What is a simple way to let a command run for 5 minutes? Kill process after it's been allowed to run for some time

I particularly like this answer:

YourCommand & read -t 300 ;  kill $!                           # 1st version

from https://superuser.com/a/1045496

However, what if I like the whole command to terminate completely if the process takes lesser time than the original specified time limit to finish?

I ask this because I am actually running this command in a subshell created by a PHP script:

// $wtime is some time limit
$cmd = "MyCommand & read -t {$wtime}; kill $!";
shell_exec($cmd);

My PHP script will not continue to the next line after shell_exec($cmd) if "read -t..." does not finish, if MyCommand finishes faster than it.

NOTE: I do not need an answer that makes use of PHP, but just the shell. That's why I am posting it here and not on Stack Overflow. However, I do welcome any answer that makes use of PHP as well.

1 Answers1

1

There is a utility that deals with this for you - timeout.

For example:

timeout 5s sleep 30
  • -s INT - By default, SIGTERM is sent, but you can change this, e.g: for SIGINT
  • -k ${DURATION} - If your application should handle the signal, but may get stuck, you can also give this argument to send a SIGKILL some time after the original signal was sent.
  • --preserve-status - If the application should handle the signal and then return a useful exit code, then you can also give this argument, otherwise timeout will return 124 if the timeout expires.
Attie
  • 20,734