- PHP Reactive Programming
- Martin Sikora
- 174字
- 2021-07-09 19:06:18
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 as it is printed using printf()
above, while being able to spawn more subprocess, if needed:
// proc_01.php $proc = proc_open('php sleep.php proc1 3', [ 0 => ['pipe', 'r'], // stdin 1 => ['pipe', 'w'], // stdout 2 => ['file', '/dev/null', 'a'] // stderr ], $pipes); stream_set_blocking($pipes[1], 0); while (proc_get_status($proc)['running']) { usleep(100 * 1000); $str = fread($pipes[1], 1024); if ($str) { printf($str); } else { printf("tickn"); } } fclose($pipes[1]); proc_close($proc);
We spawn a subprocess php sleep.php proc1 3
and then go into a loop. With a 100ms delay, we check whether there's any new output from the subprocess using fread()
. If there is, we print it; otherwise, just write the word "tick". The loop will end when the subprocess terminates (that's the condition with the proc_get_status()
function).
The most important thing in this example is calling the stream_set_blocking()
function, which makes operations with this stream non-blocking.
- Implementing Modern DevOps
- TypeScript入門與實戰(zhàn)
- Mobile Web Performance Optimization
- SQL學(xué)習(xí)指南(第3版)
- Bulma必知必會
- 數(shù)據(jù)結(jié)構(gòu)與算法分析(C++語言版)
- Swift Playgrounds少兒趣編程
- Swift 4 Protocol-Oriented Programming(Third Edition)
- 細(xì)說Python編程:從入門到科學(xué)計算
- Python 3 數(shù)據(jù)分析與機器學(xué)習(xí)實戰(zhàn)
- OpenMP核心技術(shù)指南
- PHP與MySQL權(quán)威指南
- Python青少年趣味編程
- Mastering Android Studio 3
- 零基礎(chǔ)C#學(xué)習(xí)筆記