0

If I run this unix command directly in shell:

$ sleep 100 &

sleep runs in the background as expected, and I can continue working in the command line.

but trying the same thing with shell_exec() and php I get different results.

<?php

  $sleep = $argv[1];
  $shell="sleep " . $sleep . " &";
  shell_exec($shell);

?>

when executing php sleep.php 100 the command line hangs and wont accept any more commands until sleep finishes. I am not sure whether this is a nuance I am missing with shell_exec() / $argv of php or with the unix shell.

Thanks.

BryanK
  • 1,211
  • 4
  • 15
  • 33

1 Answers1

3

The shell_exec function is trying to capture the output of the command, which it can't do while simultaneously continuing processing. In fact, if you look at the php source code, the php shell_exec function does a popen C call, which does a wait syscall on the command. wait guarantees that the subprocess doesn't return until the child has exited.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • Do you know where I can find the source code? – BryanK Oct 02 '13 at 21:37
  • I just got it from a [mirror on github](https://github.com/php/php-src.git). Start [here](https://github.com/php/php-src/blob/master/ext/standard/exec.c#L436) – kojiro Oct 03 '13 at 17:21