Fork out background processes with PHP

I found myself needing to fork out a backgroud process from within PHP so that processes that take longer than I ever want them to take (read: 10 seconds) can finish in the background.

Normally in your shell you will write something like command &, but this doesnt work with neither exec, shell_exec or system. After a bit of googling I found out that a clever solution is to use the proc_* functions.

My end result was:

<?php
proc_close( proc_open( 'command &', array(), $foo) );
?>

proc_open takes as a min. three params: string $cmd, array $descriptorspec and array &$pipes. The first one is the command you need to run, and the last two have to do with the input/output/error pipes. Pass an empty array as $descriptorspec and no pipes will be created, hence it wont hang around and wait for input for those pipes. Since we dont have any pipes, we don’t need to &$pipes array, so $foo is just there because it ain’t an optional parameter. ;)

Oh, and a new personal record - two posts in one day - whould you look at that.. :D

-fangel

October 8th, 2006 | PHP

1 comment

Comment by Egil Fujikawa Nes

Thanks a lot, exactly what I have been looking for :)

January 2, 2007, 11:31 pm

Post comment