5

I have an exe file which has the following code:

while(1)

printf("hello\n");

I'm executing this exe through php using shell_exec

$output = shell_exec('C:/Users/thekosmix/Desktop/hello.exe 2>&1');

echo $output;

now the script is executing for very long time untill i kill the process from task manager and it gives fatal error:

(Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 133693440 bytes) in C:\xampp\htdocs\shell\index.php on line 7)

I want the script (or this function) to run for a given time duration and print whatever output is generated during the time-duration not any fatal error. set_time_limit() is also not solving the problem.

Community
  • 1
  • 1
thekosmix
  • 1,705
  • 21
  • 35

3 Answers3

3

You can't do this from within PHP - set_time_limit() is only checked after each PHP statement gets executed. Under linux you'd use ulimit, but it looks like you're using Windows.

You'll need to either modify the hello.exe executable to build in a timeout, or write a wrapper that you call from PHP, which call hello.exe and handles the timeout. In any language that can easily fork, this is trivial.

Kuf
  • 17,318
  • 6
  • 67
  • 91
Cal
  • 7,067
  • 25
  • 28
  • 1
    using ulimit, how can i solve my problem?? I'm new to linux...so don't have exact idea how to use ulimit...! – thekosmix May 04 '12 at 14:42
  • `ulimit -t 3` sets the current process to only be allowed 3 seconds of CPU time. the process will be killed when this time limit is reached. Bear in mind this is CPU time, not real time. – Cal May 04 '12 at 17:53
  • u mean i can do this.. shell_exec('ulimt -t 3'); shell_exec($path_to_program); – thekosmix May 05 '12 at 06:44
  • 1
    can you please tell me how to set the time limit in shell_exec in linux using php – hiren panchal Feb 28 '14 at 08:02
1

To sum it up: do the following, if you use a Linux server:

shell_exec('ulimit -t 120 && ' . $path_to_program);

This terminates after two minutes of cpu-usage, which is a lot more than 2 minutes real time depending on the resources hunger of your program.

0

You could alter the script as so

while (shouldKeepRunning())

shouldKeepRunning could, in its most crude form, check for whether a certain file exists to determine if it should keep running. Then you just create or delete a file to shut the script down gracefully. On linux, you could use a signal handler for this, but not windows. Anyway, you get the point.

you could use ticks if the outer while loop isnt granular enough without massive code modifcation. http://php.net/manual/en/control-structures.declare.php

goat
  • 31,486
  • 7
  • 73
  • 96