Simple, cross-browser threading (forking) in php
I recently had a need to do some threaded processing in php while working on a Google Gears prototype application. As is often the case with gears, when synching the data with the online database, it'll take a while. If you're doing this explicitly and not in the background, it's nice to at least be able to update the user of the process' status using AJAX. This was my need for threading (forking in php). I wanted to run a thread to handle the update of the database and let the user sit on a page that keeps checking on the progress and updating a progress bar. Intuitive, right?
Since it had been a while since I've worked with forks in PHP I figured I'd check out Google for a tutorial on the best practice on the subject. Whoa. I got like 90 different methodologies and hardly any worked for all scenarios and cross-platform (I don't know if my project will end up on a server with windows under it or *nix). That is, until I found this blog entry by a chick named Katy. She demos the following code:
To create a fork:
function startFork($path, $file, $args) { chdir($path); if (substr(PHP_OS, 0, 3) == 'WIN') $proc = popen('start /b php "' . $path . '\\' . $file . '" ' . $args, 'r'); else $proc = popen('php ' . $path . '/' . $file . ' ' . $args . ' &', 'r'); return $proc; }
To get data from the fork:
while (!feof($proc)) { $data = fgets($proc); // Do something with the data }
0 Comments:
Post a Comment
<< Home