Skip to content

Instantly share code, notes, and snippets.

@keeguon
Created March 14, 2011 20:48
Show Gist options
  • Save keeguon/869846 to your computer and use it in GitHub Desktop.
Save keeguon/869846 to your computer and use it in GitHub Desktop.
A class to manage background processes (launch, kill, get status) in PHP.
<?php
class Process
{
protected
$command = '',
$outputFile = '',
$pidFile = ''
;
public function __construct($command, $outputFile, $pidFile)
{
$this->setCommand($command);
$this->setOutputFile($outputFile);
$this->setPidFile($pidFile);
}
/**
* Get the command
*
* @return string The command
*/
public function getCommand()
{
return $this->command;
}
/**
* Set the command
*
* @param string $command The command
*/
public function setCommand($command)
{
$this->command = $command;
}
/**
* Get the output file location
*
* @return string The output file location
*/
public function getOutputFile()
{
return $this->outputFile;
}
/**
* Set the output file
*
* @param string $outputFile The output file location
*/
public function setOutputFile($outputFile)
{
$this->outputFile = $outputFile;
}
/**
* Get the pid file location
*
* @return string The pid file location
*/
public function getPidFile()
{
return $this->pidFile;
}
/**
* Set the pid file
*
* @param string $pidFile The pid file location
*/
public function setPidFile($pidFile)
{
$this->pidFile = $pidFile;
}
/**
* Execute the process
*/
public function exec()
{
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $this->command, $this->outputFile, $this->pidFile));
}
/**
* Read the PID of the process
*
* @return integer $pid The PID of the process
*/
public function readPid()
{
$file = file($this->pidFile, FILE_SKIP_EMPTY_LINES);
$pid = $file[count($file) - 1];
return (int)$pid;
}
/**
* Find out if the process is running
*
* @return boolean
*/
public function isRunning()
{
try {
$result = shell_exec(sprintf("ps %d", $this->readPid()));
if (count(preg_split("/\n/", $result)) > 2) return true;
} catch (Exception $e) {
echo ($e->getMessage());
}
return false;
}
/**
* Kill process if running
*/
public function kill()
{
if ($this->isRunning()) {
$result = shell_exec(sprintf("kill -9 %d", $this->readPid()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment