HTTP sessions and background processes on Apache-PHP


OK , so you are all excited about running a 10 minute process and you are happy that
you have set the processing as a background process, while the user can surf along your
website / CMS. If you are are using sessions, not quite smarty !

Consider this script [parentProcess.php]

$backgroundCall = 'php childProcess.php > /dev/null &';
 
shell_exec($backgroundCall );
 
echo "Hello world ! My background job is fired";
 
// other code , redirects etc

When you call a background file with the ‘amersand’ in the end, it sure becomes a background file.
But it doesnot mean that the user will get control back of the browser. If you are using sessions,
the webpage will be busy until the background process finishes execution.

Why is that ?

[There is bug described here and it is still not solved even in the php 5.0+ versions.]

What happens is that the child process which is called by the system() ,exec() or shell_exec() command
holds the file lock on the parent process, thus locking the session file.
Thus, the session file being locked session_start(); function cannot access the file.
This is due to to open file descriptors locking the session file.Your entire session will be locked, so none of the pages of the website can be opened ( which are under session control )
unless you change the browser or delete cookies.

Solution:

There are places on the internet which provide C code and perl code to do that. But PHP has its own
function , which sadly is ignored session_write_close(); This function can be used to trigger the close of session. Thus instructing the session
that there is nothing to write until the next session start. Triggering this before firing background process will not hold locks on
the session file.

$backgroundCall = 'php childProcess.php > /dev/null &';
 
session_write_close();
 
shell_exec($backgroundCall );
 
echo "Hello world ! My background job is fired";
 
// other code , redirects etc
  • Share/Bookmark


2 Responses to “HTTP sessions and background processes on Apache-PHP”

  1.  DM Host Says:

    Hello! I just wanted to say THANKS! This saved me having to re-write my own session handler. I just wanted to add (since it might help others) that it doesn’t necessarily apply only to background threads (I am on Windows / Apache 2.2 / PHP 5.2.9-2 module).

  2.  test Says:

    Your browser does not support iframes.
    </iframe

Leave a Reply