Forum Moderators: coopster

Message Too Old, No Replies

Protecting PHP from hung CLI calls

         

l008comm

11:12 am on Dec 25, 2020 (gmt 0)

10+ Year Member Top Contributors Of The Month



I have a script that runs periodically by a launchd timer. I give the script a very tight timeout ( set_time_limit(120); ).

Most of the time, my script works great. But every once in a while, one of the commands I run in an exec( ) call seems to hang. This of course is a problem because once the exec( ) call hangs, the php script hangs as time spent on exec( ) calls does not count towards the script's runtime.

Furthermore since the script is still running, launchd doesn't call it again. So in this way, my script is entirely at the mercy of a command line program not having a problem. And if it does, I can't do anything about it.

So while I could try to figure out why my particular command seems to go awry (which is its own weird issues), the bigger issue is how can I call command line programs in php in a way that don't allow a runaway command to lock up the whole script? I wish there was an exec( )-type function with timeout built in. Or even a script timelimit function that DID count pauses and external programs. Something to kill this!? Something other than a SECOND php script that would check on the first script and kill it when there is a problem. There MUST be a better solution than that?

JorgeV

12:01 pm on Dec 26, 2020 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



Hello,

It depends of which kind of processing you are exactly doing, and how you want to handle "error" .

That being said, you can try the Linux "timeout" command.

For example, let's say , you want to execute "ping x.x.x.x" .

You can do:
exec("timeout 10 ping x.x.x.x");

This will end the command "ping", after 10 seconds.

Hope it can help.

l008comm

12:09 pm on Dec 26, 2020 (gmt 0)

10+ Year Member Top Contributors Of The Month



I'm not on linux, my OS doesn't have `timeout`. It does have a similar `timelimit` command I can install via package manager but it doesn't seem to actually work. In many tests, it has yet to ever actually kill the command in question. That would be a decent enough solution, I could even make a little wrapper for it. But no luck getting it to work.

l008comm

12:14 pm on Dec 26, 2020 (gmt 0)

10+ Year Member Top Contributors Of The Month



Just looked again and found a different program called gtimeout in homebrew, I'll try that, hopefully it works.

l008comm

12:23 pm on Dec 26, 2020 (gmt 0)

10+ Year Member Top Contributors Of The Month



Update:

`timelimit` doesn't seem to work, but `gtimeout` does.

Now, the next logical question of course is, how can I determine if a call ended because it ended on it's own, or if it ended because the gtimeout time limit was hit?