Skip to content

Instantly share code, notes, and snippets.

Created June 4, 2011 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1008090 to your computer and use it in GitHub Desktop.
Save anonymous/1008090 to your computer and use it in GitHub Desktop.
<?php
/**
* Send a command and wait for timeout
*
* How to use it?
*
$test = new Application_Model_Cmd("ping 127.0.0.1");
$test->Start();
echo $test->getBuffer();
*
*/
class Application_Model_Cmd
{
/**
* Input/Output write/read
*
* @var type
*/
private $descriptorspec = array(1=> array("pipe", "w"));
/**
* Process resource
* @var type
*/
private $process = null;
private $pipes = null;
private $emptyarr = null;
private $pipesdup = null;
/**
* Which command to run
* @var type
*/
private $cmd = null;
/**
* How many seconds after the process should end
* @var type
*/
private $timer = null;
/**
* Stopwatch for seconds
* @var type
*/
private $start = null;
/**
* Single line
* @var type
*/
private $buffer = null;
/**
* Whole buffer
* @var type
*/
private $fullbuffer = null;
/**
* Initilize the command
*/
public function __construct($cmd="ping6 ::1", $timer=5)
{
$this->cmd = $cmd;
$this->timer = $timer;
}
/**
* Execute the command
*/
public function Start()
{
$this->process = proc_open($this->cmd,
$this->descriptorspec,
$this->pipes);
$this->emptyarr = array();
$this->start = microtime(true);
if (is_resource($this->process))
{
stream_set_blocking($this->pipes[1], 0);
while (microtime(true) - $this->start < 5)
{
$this->pipesdup = $this->pipes;
if (stream_select($this->pipesdup, $this->emptyarr,
$this->emptyarr, 0, 100000))
{
$this->buffer = fread($this->pipes[1], 100);
$this->fullbuffer .= $this->buffer;
}
}
$this->Stop();
}
}
/**
* Stop the process when requires
*
*/
private function Stop()
{
fclose($this->pipes[1]);
proc_terminate($this->process);
}
/**
* Get the command output
*
* @return type
*/
public function getBuffer()
{
return $this->fullbuffer;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment