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.