Skip to content

Instantly share code, notes, and snippets.

@shoghicp
Created January 12, 2013 12:24
Show Gist options
  • Save shoghicp/4517781 to your computer and use it in GitHub Desktop.
Save shoghicp/4517781 to your computer and use it in GitHub Desktop.
async PHP Console I/O, Needs pthreads https://github.com/krakjoe/pthreads/
<?php
if(!extension_loaded("pthreads") and @dl((PHP_SHLIB_SUFFIX === "dll" ? "php_":"") . "pthreads." . PHP_SHLIB_SUFFIX) === false){
trigger_error("Unable to find pthreads extension", E_USER_ERROR);
exit(1);
}
function kill($pid){
$uname = strtoupper(php_uname("s"));
if(strpos($uname, "WIN") !== false){
$os = "win";
}elseif(strpos($uname, "DARWIN") !== false){
$os = "mac";
}else{
$os = "linux";
}
switch($os){
case "win":
ob_start();
passthru("%WINDIR%\\System32\\taskkill.exe /F /PID ".((int) $pid));
ob_end_clean();
break;
case "mac":
case "linux":
default:
ob_start();
passthru("kill -9 ".((int) $pid));
ob_end_clean();
}
}
class ConsoleLoop extends Thread{
var $line = false, $stop = false;
public function run(){
$fp = fopen("php://stdin", "r");
while($this->stop === false and ($line = fgets($fp)) !== false){
$this->line = $line;
$this->wait();
$this->line = false;
}
exit(0);
}
}
class ConsoleIO{
private $loop;
public function __construct(){
$this->loop = new ConsoleLoop;
$this->loop->start();
}
public function __destruct(){
$this->loop->stop = true;
$this->loop->notify();
$this->loop->join(); //segfault lol
}
public function input($block = false){
do{
if($this->loop->line !== false){
$line = trim($this->loop->line);
$this->loop->notify();
return $line;
}
usleep(1);
}while($block === true);
return false;
}
public function output($output, $EOL = true){
echo $output . ($EOL === true ? PHP_EOL : "");
}
}
$io = new ConsoleIO;
$io->input(true); //if block == true, this function will only return when input is available
//Warning! pthreads implementation in PHP is buggy. When closing the script, you'll have to kill it.
kill(getmypid()); //Fix for segfault
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment