0

I've a question about this answer php execute a background process

Can anyone provide me a working simple example to try what the answer explains?

Thanks in advance!

Alberto

Community
  • 1
  • 1
albertopriore
  • 614
  • 2
  • 9
  • 36
  • That answer is is wrong in any context other than a shell session, and that failure to complete is an a likely outcome - the spawned process is not dissociated from the session, it merely runs in parallel until the session ends. Are you sure this applies to your scenario? – symcbean Dec 16 '10 at 17:19

1 Answers1

2

On linux box only:

result.php

<?php
$cmd = 'for i in {1..5}; do date; sleep 2; done';
$outputfile = '/tmp/result.txt';
$pidfile = '/tmp/result.pid';
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
?>

in command line:

php result.php;
tail /tmp/result.txt; /* to monitor the results, take 10 seconds to complete */
cat /tmp/result.pid   /* the pid registered */
ajreal
  • 46,720
  • 11
  • 89
  • 119