The proc_open() and non-blocking fread()
Our goal is to have the means to start various subprocesses asynchronously. In this example, we'll use a simple PHP script that'll just sleep for a couple of seconds and represent our asynchronous task:
// sleep.php $name = $argv[1]; $time = intval($argv[2]); $elapsed = 0; while ($elapsed < $time) { sleep(1); $elapsed++; printf("$name: $elapsed\n"); }
This script takes two arguments. The first one is an identifier of our choice that we'll use to distinguish between multiple processes. The second one is the number of seconds this script will run while printing its name and the elapsed time every second. For example, we can run:
$ sleep.php proc1 3 proc1: 1 proc1: 2 proc1: 3
Now, we'll write another PHP script that uses proc_open()
to spawn a subprocess. Also, as we said, we need the script to be non-blocking. This means that we need to be able to read output from the subprocess...