1

The scenario:

  1. I have a PHP script (accessed via the web) which generates a shell script which needs to continue to run even after the request ends.
  2. I need the output sent to a file on disk (i.e. "./script.sh > run.log")

Every approach I try seems to result in PHP still waiting for the shell script to finish executing. Approaches I've tried:

  1. nohup ./script.sh > run.log &
  2. nohup ./script.sh > run.log 2>&1
  3. nohup ./script.sh > run.log 2>&1 &
  4. ./script.sh &
  5. ./script.sh > run.log 2>&1
  6. ./script.sh > run.log &

I think there's something really obvious I might be missing. Any ideas?

Zach Bloomquist
  • 5,309
  • 29
  • 44
  • Does the shell script need to be run as the same user as your web server runs? What about running a daemon of some sort to launch the shell script, and have your PHP script simply send a trigger to the daemon? Also, does your PHP script really need to *generate* the shell script? That seems very risky to me. – ghoti Mar 24 '16 at 20:47

3 Answers3

2

I think you could achieve this by starting a screen instance with the script:

screen -d -m 'bash ./script.sh > run.log'
tschoffelen
  • 518
  • 7
  • 21
1

Have you tried shell_exec ?

You might be interested in this post : Is there a way to use shell_exec without waiting for the command to complete?

Community
  • 1
  • 1
Cédric Françoys
  • 870
  • 1
  • 11
  • 22
1

Your number 5 approach is close but you need to combine it with 6 like this

shell_exec("/script.sh > run.log 2>&1 &");

Or redirect to /dev/null like this

shell_exec("/script.sh > /dev/null 2>/dev/null &")

It appears that the PHP development server cannot fork off commands properly. Using a real web server like Apache or NGinx will resolve the issue.

Tim Penner
  • 3,551
  • 21
  • 36
  • I made that change and the PHP is still blocking until the shell script finishes executing. Do you think that's because I'm using PHP's built-in web server? Would switching to nginx/php-fpm fix it? – Zach Bloomquist Mar 28 '16 at 18:44
  • I installed nginx/php-fpm and that resolved the issue. **It appears that the PHP development server cannot fork off commands properly.** – Zach Bloomquist Mar 29 '16 at 18:55