Reputation: 2874
I am calling a shell script in Linux using a PHP script, I do the following:
shell_exec('./shell_script.sh');
after this the PHP script continues on.. All this works as expected.
However, sometimes the shell_script doesn't finish executing for whatever reason, so here is the question:
How can I terminate the shell_script.sh after being executed for x amount of time? Should this be dealt with in PHP itself somehow (dont think that's possible in this instance) or should it be done in the .sh itself?
So just after the:
#!/bin/bash
at the beginning of the .sh, is there something I can put for it to terminate if execution time exceeds say 20 seconds perhaps?
Upvotes: 1
Views: 1119
Reputation: 111269
You could use something like this:
# start timer
( sleep $TIMEOUT ; kill $$ ) 2>/dev/null &
TIMER_PID=$!
# "payload"
echo hello
# cancel timer
kill $TIMER_PID
YMMV though, in my tests the part that is supposed to cancel the timer sometimes doesn't kill sleep
and the program waits until the timeout finishes.
Upvotes: 1
Reputation: 10840
I don't know if you can do it in php, and there may exist better solutions in bash, but this is what you could do:
This is the line you can put immediately after #!/bin/bash
to kill the current script after 20 seconds:
(sleep 20 && kill $$) &
bash replaces $$ with the pid of the current script.
Upvotes: 3