开发者

php background process PID problem

I have this script and if I run it I get a different PID number entered in the database from the one that is listed with the top command:

<?php
error_reporting(0);

include_once "config/mysql.php";

// the path
$path = "PATH=$PATH:/share/MD0_DATA/.qpkg/Optware/bin:";

//random number for the log file name
$random = rand(1,500000);

//initial download location
$init_loc="/share/MD0_DATA/Qdownload/plowshare";

$items = rtrim($_POST['items'],",");
$sql = mysql_query("SELECT url, pid FROM plow WHERE id IN ($items)") or die ('Error: ' . mysql_error());

while ($db_row = mysql_fetch_assoc($sql)) { 
  //random number for the log file name
  $random = rand(1,500000);
  //log file name
  $out_file = '/share/MD0_DATA/Qdownload/plowshare/Logs/log'.$random.'.txt';
  //command 1
  $command = exec("($path" . " nohup /opt/bin/plowdown -o '$init_loc' " . "'".$db_row['url']."' 2> " . "'$out_file' > /dev/null &);" . "echo $$;", $out); 
  exec($command, $out);
  $query = mysql_query("UPDATE plow SET state = 'Active', pid = '$out[0]' WHERE id IN ($items)") or die ('Error: ' . mysql_error());
 }
mysql_close();

?>

The result is always the same:

Pid number entered in the database : 11159 (random number, choosen now just to make a point)

Pid number listed with the top commnand: 11161.

开发者_如何学Python

The PID number listed with the top command is always bigger then the one from the database by 2.

It drives me crazy ...

Thanks,

Cristian.


$$ returns the PID of the script that runs a command, not the PID of the last executed command. Per example, echoing $$ in a bash shell typically returns the PID of bash itself. Echoing $$ from a script returns the PID of the script.

So, the reason why you get a +2 difference is because:

  • exec() spawns a "shell" with PID 1
  • nohup is executed with PID 2
  • /usr/bin/plowdown is executed with PID 3
  • echo $$ returns the PID of the shell, which is 1


Like netcoder says, you can't use $$, but rather $! which returns the pid of the last backgrounded process. Try something like this

$command = exec("($path" . " nohup /opt/bin/plowdown -o '$init_loc' " . "'".$db_row['url']."' 2> " . "'$out_file' > /dev/null ) & " . 'echo ${!};', $out); 

Notice & outside the parenthesis and no semi-colon after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜