Busted Mug

A blog that documents solutions to the most frustrating problems that occur during development in technologies such as Java, XML, AJAX, SQL, CSS and others that make me want to throw my coffee mug against the cube wall.

Saturday, March 01, 2008

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)

  if (substr(PHP_OS, 0, 3) == 'WIN')
    $proc = popen('start /b php "' . $path . '\\' . $file . '" ' . $args, 'r');
    $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
This methodology is great because it seems to always fit. It's pretty easy to understand too. It does involve some OS calls but has conditions for for windows and *nix, which is ok by me. It's a simple method that starts a new process for the thread. I plan to implement post haste. I'd recommend this if you need to do some threading (forking, I wish Java and PHP would get on the same page as far as terminology is concerned).

Labels: , , , , ,


Post a Comment

<< Home