<?php
/**
 * An easy way to keep in track of external processes.
 * Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
 *
 * via http://www.php.net/manual/en/function.exec.php#88704
 *
 * @compability: Linux only. (Windows does not work).
 * @author: Peec
 */
class Process{
    private $pid;
    private $command;

	public static function ensureRunning($cmd, $pidfile, $restart = false) {
		$pidfile = '/var/run/' . $pidfile;
		// get pid from pidfile, protecting against invalid data
		$p1 = null;
		if (file_exists($pidfile) && is_readable($pidfile)) {
			$pid = substr(file_get_contents($pidfile), 0, 64);
			$p1 = new Process();
			$p1->setPid($pid);
		}
		if ($restart && $p1) {
			$p1->stop();
		}
		// check whether process with this pid is running
		if (!$p1 || !$p1->status()) {
			// check that we can write the pidfile, to avoid spawning endless processes
			if (file_put_contents($pidfile, 'test')) {
				$p2 = new Process($cmd);
				file_put_contents($pidfile, $p2->getPid());
			}
			return true;
		}
		return false;
	}

    public function __construct($cl=false){
        if ($cl != false){
            $this->command = $cl;
            $this->runCom();
        }
    }
    private function runCom(){
        $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $this->pid = (int)$op[0];
    }

    public function setPid($pid){
        $this->pid = $pid;
    }

    public function getPid(){
        return $this->pid;
    }

    public function status(){
        $command = 'ps -p '.$this->pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }

    public function start(){
        if ($this->command != '')$this->runCom();
        else return true;
    }

    public function stop(){
        $command = 'kill '.$this->pid;
        exec($command);
        if ($this->status() == false)return true;
        else return false;
    }
}
?>
