CLI process for PHP does not terminate when executed

I have this in a single PHP file:

echo shell_exec('nohup /usr/bin/php -f '.CRON_DIRECTORY.'testjob.php > /dev/null 2>&1 &'); 

and in testjob.php I have:

 file_put_contents('test.txt',time()); exit; 

And all this only works dandy. However, if I switch to processes, this is not the end of testjob.php after it starts.

+4
source share
3 answers

Remove & from the end of your team. This symbol tells nohup to continue to run in the background, so shell_exec waiting for the task to complete ... and waiting ... and waiting ... until the end of time;)

I don’t even understand why you are executing this command with nohup .

 echo shell_exec('/usr/bin/php -f '.CRON_DIRECTORY.'testjob.php > /dev/null 2>&1'); 

should be enough.

0
source

(To post this as an answer instead of a comment since stackoverflow still doesn't allow me to post comments ...)

It works for me. I did testjob.php exactly as described, and another test.php file with only this line (except that I deleted CRON_DIRECTORY because testjob.php was in the same directory for me).

To be sure that I measured correctly, I added "sleep (5)" at the top of testjob.php, and in another window:

 watch 'ps a |grep php' 

works. It happens:

  • I run test.php
  • test.php exits right away, but testjob.php appears in my list
  • After 5 seconds, it disappears.

I was wondering if the shell can make a difference, so I switched from bash to sh. The same result.

I also thought if this could be because your external script has been running for a long time. So I put "sleep (10)" at the bottom of test.php. The same result (i.e. Testjob.php ends after 5 seconds, test.php ends 5 seconds after that).

So, it's no use, your problem is somewhere other than the code you posted.

+1
source

You are executing PHP and doing this is a background task. This means that it will run in the background until it is complete. shell_exec will not kill this process or something like that.

You might want to set an execution limit, PHP cli has a setting with no default restrictions . See Also set_time_limit PHP Manual ;

So, if you are wondering why the php process does not end, you need to debug the script. If this is too complicated, and you cannot find out why the script lasts, you can simply terminate the process after a while, for example. 1 minute.

0
source

All Articles