php脚本-将输入重定向到另一个实例


php script - Redirect input to another instance

我有一个php脚本谁使用flock()拒绝多个实例,如果脚本已经运行

我希望在脚本调用中提供的参数被转移到能够处理它们的现有进程。

ie:

test.php:

#!/usr/bin/env php
<?php
$lock_file = fopen ( getcwd () . '/'. basename(__FILE__, '.php') . '.pid', 'c' );
$got_lock = flock ( $lock_file, LOCK_EX | LOCK_NB, $wouldblock );
if ($lock_file === false || (! $got_lock && ! $wouldblock)) :
    throw new Exception ( "Error opening or locking lock file" );
    error_log("execption thrown");
elseif (! $got_lock && $wouldblock) :
    exit ( "Another instance is already running; terminating.'n" );
endif;
while (true) :
    $input = $argv; // or incomming datas from other script ?
    unset($argv);
    if (is_array($input)) :
        foreach ($input as $a) :
            echo $a;
        endforeach;
    else :
        echo $input;
    endif;
endwhile;
?>

现在,如果我运行:

php -f test.php arg1 arg2

php -f test.php arg3 arg4

第二个调用也退出了,但我希望arg3和arg4被管道连接到主进程。

换句话说,您想要一种与已经存在的进程进行通信的方法?IPC,有很多方法可以做到这一点。绝对最快的方式是共享内存。但是使用数据库或Unix套接字将更容易实现。下面是一个使用SQLite的例子:

只要方便处理消息,就这样做:

while(NULL!==($message=check_for_message())){//handle all messages
echo "got a mesage!:";
var_dump($message);
}

和"check_for_message"函数:

//returns string("message") if there is a message available.
// else returns NULL
//Warning, do not try to optimize this function with prepared statements, unless you know what you're doing, in SQLIte they will lock the database from writing.
function check_for_message(){
static $db=false;
if($db===false){
$db=new PDO('sqlite:ipc.db3','','',array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->exec(
'
CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT);
'
);
register_shutdown_function(function()use(&$db){
$db=NULL;
unset($db);
unlink("ipc.db3");
});
}
$message=$db->query("SELECT id,message FROM messages LIMIT 1",PDO::FETCH_ASSOC);
foreach($message as $ret){
$db->query("DELETE FROM messages WHERE id = ".$db->quote($ret['id']));
return $ret['message'];
}
return NULL;
}

和发送消息:

使用例子:

foreach($argv as $arg){
sendmessage($arg);
}

功能:

function sendmessage(string $message){
$db=new PDO('sqlite:ipc.db3','','',array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
$db->query('INSERT INTO messages (message) VALUES('.$db->quote($message).');');
}

注释:我认为你可以通过使用WAL-mode sqlite和prepared语句来优化这个函数。我认为你可以通过使用PDO::ATTR_PERSISTENT把它放在共享内存中来优化它,但是我说,这是使用未记录的功能的黑客行为,我不希望它适用于像HHVM PHP这样的东西。在unix (*BSD, Mac OS X, Linux等)上,使用unix套接字会更快。使用原始共享内存会更快,但是在共享内存中实现消息队列有点棘手。您还可以考虑安装信号处理程序,例如SIGUSR1,以指示有消息等待,请参阅http://php.net/manual/en/function.pcntl-signal.php