Thursday, March 27, 2014

Run PHP As a Background Process

I would like to run a PHP script as a background process on my OSX machine. In the test script, I use file_put_contents method to write the log in a specific file.  When I directly execute the command line PHP script, I can see that the log is written into the file, which means, everything is fine. But, when I use it as a background process, it is not working. I have tried many ways that just failed to run script as a background process. At the end, I solve the problem. I want to record how I make it work at the end.

The commands which I used were failed:

 php /path/to/my/test/script/cli_test.php argument1 &
 php -f /path/to/my/test/script/cli_test.php argument1 & 
 php /path/to/my/test/script/cli_test.php argument1 > output.txt 2>&1 &
 nice -20 php  /path/to/my/test/script/cli_test.php argument1 > output.txt 2>&1 &
 nohup  /path/to/my/test/script/cli_test.php argument1 1>/dev/null 2>/dev/null &
 php /path/to/my/test/script/cli_test.php argument1 > /dev/null 2>&1 & echo $! 

The result I got was always showing a sudden stop like below -

 [1]+  Stopped     nohup php /path/to/my/test/script/cli_test.php argument1 > /dev/null 2> /dev/null

And, the process keeps hanging in the background, never die.

I found the solution in a discussion - http://ubuntuforums.org/showthread.php?t=977332 .
According to the discussion that the discussion says, I tried the following command and it worked very well.


php -q /path/to/my/test/script/cli_test.php argument1 < /dev/null
nohup php -q /path/to/my/test/script/cli_test.php argument1 </dev/null 2> /dev/null & echo $! 

I do not know where the bug sits, is it a PHP command line or OSX bug? Ubuntu users think it is a OS level bug, but it seems to me it is a PHP command line bug. Anyways, as long as it works and I do not have to use other solution like "pcntl_fork".


1 comment: