mkolecki/sub-process

Library for creating new processes for PHP

dev-master 2019-09-20 22:30 UTC

This package is auto-updated.

Last update: 2025-06-21 23:02:15 UTC


README

Build Status

sub-process

PHP process forking made easy.

This library will help you to fork process and manage it state.

Install

composer require mkolecki/sub-process

Usage

RealPcntl fork and communication

To fork to sub-process first create SubProcess\Process instance and then call start() method.

To controll what new Process will do, you have to pass callable. That callable will receive Process instance which has Channel to send() and read() messages between parrent and child process.

Example examples/02-channel-communication.php:

<?php
include __DIR__ . '/../vendor/autoload.php';

use SubProcess\Child;
use SubProcess\Process;

$process = new Process(function (Child $child) {
    $channel = $child->channel();

    $channel->send("Hello from child process!");
    $channel->send(["You", " can ", "send even arrays!"]);

    $object = new \stdClass();
    $object->inFact = "you can send any";
    $object->serialisable = ['value'];

    $channel->send($object);
});

$process->start();

while (!$process->channel()->eof()) {
    var_dump($process->channel()->read());
}

$exitStatus = $process->wait();
var_dump($exitStatus->code());
$ php examples/02-channel-communication.php

Output:

string(25) "Hello from child process!"
array(3) {
  [0]=>
  string(3) "You"
  [1]=>
  string(5) " can "
  [2]=>
  string(17) "send even arrays!"
}
object(stdClass)#5 (2) {
  ["inFact"]=>
  string(16) "you can send any"
  ["serialisable"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
int(0)