Skip to content

Commit e8f4154

Browse files
committed
[Process] Add support for Fiber
1 parent 12f8fae commit e8f4154

File tree

3 files changed

+51
-2
lines changed

3 files changed

+51
-2
lines changed

src/Symfony/Component/Process/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
5.4
5+
---
6+
7+
* Add support for `Fiber`
8+
49
5.2.0
510
-----
611

src/Symfony/Component/Process/Process.php

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -427,12 +427,32 @@ public function wait(callable $callback = null)
427427
do {
428428
$this->checkTimeout();
429429
$running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
430-
$this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
430+
431+
if (class_exists(\Fiber::class, false) && $fiber = \Fiber::getCurrent()) {
432+
$this->readPipes(false, '\\' !== \DIRECTORY_SEPARATOR || !$running);
433+
$startedAt = microtime(true);
434+
$fiber->suspend();
435+
$sleepFor = (int) (1000 - (microtime(true) - $startedAt) * 1000000);
436+
if (0 < $sleepFor) {
437+
usleep($sleepFor);
438+
}
439+
} else {
440+
$this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
441+
}
431442
} while ($running);
432443

433444
while ($this->isRunning()) {
434445
$this->checkTimeout();
435-
usleep(1000);
446+
if (class_exists(\Fiber::class, false) && $fiber = \Fiber::getCurrent()) {
447+
$startedAt = microtime(true);
448+
$fiber->suspend();
449+
$sleepFor = (int) (1000 - (microtime(true) - $startedAt) * 1000000);
450+
if (0 < $sleepFor) {
451+
usleep($sleepFor);
452+
}
453+
} else {
454+
usleep(1000);
455+
}
436456
}
437457

438458
if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {

src/Symfony/Component/Process/Tests/ProcessTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,30 @@ public function testMustRun()
550550
$this->assertEquals('foo'.\PHP_EOL, $process->getOutput());
551551
}
552552

553+
/**
554+
* @requires PHP 8.1
555+
*/
556+
public function testMustRunWithFiber()
557+
{
558+
$process = new Process(['sleep', 1]);
559+
$fiber = new \Fiber(function () use ($process) {
560+
$process->mustRun();
561+
});
562+
$fiber->start();
563+
564+
$fiberHasBeenSuspended = false;
565+
while (!$fiber->isTerminated()) {
566+
$fiberHasBeenSuspended = true;
567+
$this->assertTrue($fiber->isSuspended());
568+
$fiber->resume();
569+
570+
usleep(900);
571+
}
572+
573+
$this->assertTrue($process->isTerminated());
574+
$this->assertTrue($fiberHasBeenSuspended);
575+
}
576+
553577
public function testSuccessfulMustRunHasCorrectExitCode()
554578
{
555579
$process = $this->getProcess('echo foo')->mustRun();

0 commit comments

Comments
 (0)