Skip to content

Commit 219a653

Browse files
author
Florian Eckerstorfer
committed
Merge pull request #3 from cocur/stop
Added stop method to BackgroundProcess
2 parents 983a939 + ce9c9e5 commit 219a653

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

src/BackgroundProcess.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,23 @@ public function isRunning()
6969
return false;
7070
}
7171

72+
/**
73+
* Stops the process.
74+
*
75+
* @return boolean `true` if the processes was stopped, `false` otherwise.
76+
*/
77+
public function stop()
78+
{
79+
try {
80+
$result = shell_exec(sprintf('kill %d 2>&1', $this->pid));
81+
if (!preg_match('/No such process/', $result)) {
82+
return true;
83+
}
84+
} catch (Exception $e) {}
85+
86+
return false;
87+
}
88+
7289
/**
7390
* Returns the ID of the process.
7491
*

tests/BackgroundProcessTest.php

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
/**
1111
* BackgroundProcessTest
1212
*
13-
* @category Test
13+
* @category test
1414
* @package cocur/background-process
1515
* @author Florian Eckerstorfer <[email protected]>
1616
* @copyright 2013-2104 Florian Eckerstorfer
@@ -26,13 +26,17 @@ class BackgroundProcessTest extends \PHPUnit_Framework_TestCase
2626
* @covers Cocur\BackgroundProcess\BackgroundProcess::run()
2727
* @covers Cocur\BackgroundProcess\BackgroundProcess::isRunning()
2828
* @covers Cocur\BackgroundProcess\BackgroundProcess::getPid()
29+
* @covers Cocur\BackgroundProcess\BackgroundProcess::stop()
2930
*/
3031
public function testRun()
3132
{
32-
$process = new BackgroundProcess('sleep 1');
33-
$this->assertFalse($process->isRunning());
33+
$process = new BackgroundProcess('sleep 5');
34+
$this->assertFalse($process->isRunning(), 'process should not run');
3435
$process->run();
35-
$this->assertNotNull($process->getPid());
36-
$this->assertTrue($process->isRunning());
36+
$this->assertNotNull($process->getPid(), 'process should have a pid');
37+
$this->assertTrue($process->isRunning(), 'process should run');
38+
$this->assertTrue($process->stop(), 'stop process');
39+
$this->assertFalse($process->isRunning(), 'processes should not run anymore');
40+
$this->assertFalse($process->stop(), 'cannot stop process that is not running');
3741
}
3842
}

0 commit comments

Comments
 (0)