All pastes #459667 Raw Edit

Unnamed

public php v1 · immutable
#459667 ·published 2007-04-26 16:42 UTC
rendered paste body
/**here is classes to run pipe :*/$pipe = new Pipe();# or $pipe = new PipeIO();$cmd='ps';$args = array();$result = $pipe->run($cmd, $args, $stdin='');if($result == false)	echo "error : " . $pipe->get_error();else	echo "result = $result\n";// an other example : will execute a php script and return the result.$pipe = new Pipe();$cmd='php.exe';$args = array('-q');$script = '<?php phpinfo(); ?>';$result = $pipe->run($cmd, $args, $script);if($result == false)	echo "error : " . $pipe->get_error();else	echo "result = $result\n";class PipeIO{	protected $descriptor_spec;	protected $cmd;	protected $args;	protected $pipes;	protected $stdin_data;	protected $stdout_data;	protected $stderr_data;	protected $terminated;	public function __construct(){		$this->descriptor_spec = array(			0 => array("pipe", "r"),  // stdin is a pipe that the child will read from			1 => array("pipe", "w"),  // stdout is a pipe that the child will write to			2 => array("pipe", "w")   // stderr is a file to write to		);		$this->proc_id = null;	}	public function __destruct(){		$this->terminate();	}	public function terminate(){				if($this->proc_id != null){			proc_close($this->proc_id);			$this->proc_id = null;		}	}	public function run($cmd, $args, $stdin_data=null){		$this->cmd = $cmd;		$this->args = $args;		$this->stdin_data = $stdin_data;		$this->stderr_data = '';		$this->stdout_data = '';		$this->terminated = false;		$this->pipes = null;		$cmd = $this->cmd . ' ' . join(' ', $this->args);		$this->proc_id = proc_open($cmd, $this->descriptor_spec, $this->pipes);		# if (is_resource($this->proc_id)) {		if ($this->proc_id !== false) {			echo "running pipe\n";			$ids[0] = Gtk::io_add_watch($this->pipes[1],Gtk::IO_HUP, array($this, 'io_hup'));			$ids[1] = Gtk::io_add_watch($this->pipes[1],Gtk::IO_IN,  array($this, 'stdout'));			# $ids[2] = Gtk::io_add_watch($this->pipes[2],Gtk::IO_IN,  array($this, 'stderr'));			if($this->stdin_data != null){				fwrite($this->pipes[0], $this->stdin_data);				fflush($this->pipes[0]);			}			fclose($this->pipes[0]);			# will terminate when io_hup() is called.			Gtk::main();			fclose($this->pipes[1]);			fclose($this->pipes[2]);			$this->terminate();			return $this->stdout_data;		} else{			trigger_error("PipeIO::run() : proc_open error");			return false;		}	}		function io_hup($pipe){		$this->terminated = true;		# this pipe exec is done ;		Gtk::main_quit();		return false;	}		function stdout($pipe){		while($data =  fgets($pipe)){			# echo $data;			$this->stdout_data .= $data;		}		if(feof($pipe)){			return false;		}		return $this->terminated;	}		function stderr($pipe){		while($data=  fgets($pipe)){			echo $data;			$this->stderr_data .= $data;		}		if(feof($pipe)){			return false;		}		return $this->terminated;	}}