Reputation: 102
Summary: I have a command that runs on a PHP page, called by Ajax.
Latest PHP example:
$linuxCmd = "cd ~/apps && node app.js > scr_log.log 2>&1 &";
exec($linuxCmd);
I've also tried:
$linuxCmd = "cd ~/apps && node app.js > scr_log.log 2>&1";
$linuxCmd = "cd ~/apps && node app.js &";
$linuxCmd = "cd ~/apps && node app.js > /dev/null 2>&1 &";
$linuxCmd = "cd ~/apps && node app.js 2>&1 /dev/null &";
And think over the past day I've covered every possible other combination of those commands. It seems that no matter what I've tried, the ajax success function on previous page does not run. I thought that running the process above in the background would let the PHP page return back to the ajax call on the javascript page and continue running scripts, but no luck.
I've also tried adding exit()
and return()
after the exec()
function, but it's not reaching them.
Also, the script (app.js) runs in a loop. It is terminated when a value in the database changes as it checks that every time it runs in the loop. I also have a way to kill the process, which works fine and returns to the success function of that ajax request, because it just terminates the process.
To put it another way, I need the script that I'm running from PHP exec() to constantly run after started, but also need my front end javascript page to continue after starting that process in the backend.
I'm wondering if this is maybe not possible for some reason. And if so, if there is a better way than PHP's exec() function. Also tried shell_exec with a couple of the above combinations.
Upvotes: 0
Views: 266
Reputation: 42711
Tilde expansion is a function of the shell, not something intrinsic to Linux, so your script should not rely on it working. Even if that weren't the case, web servers generally run as a separate user that doesn't have a home directory. What you should do is use absolute paths throughout your script, and don't try to write into a user directory with the web server user.
<?php
$linuxCmd = "/usr/bin/node /home/user/apps/app.js > /var/log/scr_log.log 2>&1 &";
exec($linuxCmd);
Letting your web server write to /var/log
may require some permissions tweaks, but best to put things where they belong. You don't want to give something exposed to the outside – like a web server – permissions to write into a sensitive location like a home directory.
As for how best to run the command persistently in the background, see the answers to this question. There's nothing in your code that would prevent an Ajax function from returning successfully; this would only happen if the address was wrong (i.e. 404) or an error occurred (e.g. 500.)
Upvotes: 2