How to start a background process with PHP exec (linux)?
I know there's a lot of posts on this topic, but all solutions mentioned there don't seem to work for me.
I'm building a chat client and I want to keep a process running in the background, that will listen for incoming messages on my account.
Here's the code:
$command = "cd classes/chat/inc/ && /usr/bin/php5 client.php --mysql_server=localhost --mysql_username=root --mysql_password= --mysql_database=covide --gtalk_user=xxx --gtalk_password=xxx --user_id=".$_SESSION['user_id']." &> 开发者_开发百科/dev/null &";
exec($command);
I've tried a lot of options instead of this:
&> /dev/null &
like > /dev/null 2>/dev/null & or > testoutput.php 2>&1 & echo $! (from various posts on this forum), but to no success. Does anyone have an idea on how this should be fixed?
I have a working version of just this. But instead of using exec(); we use a curl POST to run our background process. The problem is the timing out limitations. What you can do is have your background process run through the "listen for incoming messages" task, then at the end call another instance of itself and close the current instance.
You can use something like this at the beginning of your process to make sure that it doesn't exit prematurely, but I did not find that this was necessary, it ran fine even when the following wasn't implemented, still:
/* Close our connection with calling file */
while(ob_get_level()) ob_end_clean();
header('Connection: close');
ignore_user_abort();
ob_start();
echo('Running in the background.');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
The following command should return immediately:
exec('nohup php otherscript.php > nohup.out & > /dev/null');
See the full answer here for a more overview how you can manage the execution cycle of the background script.
精彩评论