The following function takes an array of shell commands and executes them. It is able to execute up to $nb_max_process at the same time. As soon as one process is terminated, another one is executed. Quite useful if you want to batch process commands on a multi-processor or multi-core environment.
The example below tries to convert to PNG a list of SVG files submitted on the command line (using Inkscape).
(it's quick and dirty but works very well for me)
#!/usr/bin/php
<?php
function pool_execute($commandes,$nb_max_process) {
$pool=array();
for($i=0;$i<$nb_max_process;$i++) {
$pool[$i]=FALSE;
}
while(count($commandes)>0) {
$commande=array_shift($commandes);
$commande_lancee=FALSE;
while($commande_lancee==FALSE) {
usleep(50000);
for($i=0;$i<$nb_max_process and $commande_lancee==FALSE;$i++) {
if($pool[$i]===FALSE) {
$pool[$i]=proc_open($commande,array(),$foo);
$commande_lancee=TRUE;
} else {
$etat=proc_get_status($pool[$i]);
if($etat['running']==FALSE) {
proc_close($pool[$i]);
$pool[$i]=proc_open($commande,array(),$foo);
$commande_lancee=TRUE;
}
}
}
}
}
}
$fichiers=$argv;
array_shift($fichiers);
$commandes=array();
foreach($fichiers as $fichier) {
$entree=$fichier;
$sortie=basename($fichier,'.svg').".png";
$commandes[]='inkscape --file='.escapeshellarg($entree).' --export-area-canvas --export-png='.escapeshellarg($sortie);
}
pool_execute($commandes,4);