PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
Loading...
Searching...
No Matches
ConsoleReaderChildProcess.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\console;
25
26use pmmp\thread\Thread as NativeThread;
27use pmmp\thread\ThreadSafeArray;
29use function cli_set_process_title;
30use function count;
31use function dirname;
32use function fwrite;
33use function is_numeric;
34use const PHP_EOL;
35use const STDOUT;
36
37if(count($argv) !== 2 || !is_numeric($argv[1])){
38 echo "Usage: " . $argv[0] . " <command token seed>" . PHP_EOL;
39 exit(1);
40}
41
42$commandTokenSeed = (int) $argv[1];
43
44require dirname(__DIR__, 2) . '/vendor/autoload.php';
45
46@cli_set_process_title('PocketMine-MP Console Reader');
47
49$channel = new ThreadSafeArray();
50$thread = new class($channel) extends NativeThread{
54 public function __construct(
55 private ThreadSafeArray $channel,
56 ){}
57
58 public function run() : void{
59 require dirname(__DIR__, 2) . '/vendor/autoload.php';
60
61 $channel = $this->channel;
62 $reader = new ConsoleReader();
63 while(true){ // @phpstan-ignore-line
64 $line = $reader->readLine();
65 if($line !== null){
66 $channel->synchronized(function() use ($channel, $line) : void{
67 $channel[] = $line;
68 $channel->notify();
69 });
70 }
71 }
72 }
73};
74
75$thread->start(NativeThread::INHERIT_NONE);
76while(true){
77 $line = $channel->synchronized(function() use ($channel) : ?string{
78 if(count($channel) === 0){
79 $channel->wait(1_000_000);
80 }
81 return $channel->shift();
82 });
83 $message = $line !== null ? ConsoleReaderChildProcessUtils::createMessage($line, $commandTokenSeed) : "";
84 if(@fwrite(STDOUT, $message . "\n") === false){
85 //Always send even if there's no line, to check if the parent is alive
86 //If the parent process was terminated forcibly, it won't close the connection properly, so feof() will return
87 //false even though the connection is actually broken. However, fwrite() will fail.
88 break;
89 }
90}
91
92//For simplicity's sake, we don't bother with a graceful shutdown here.
93//The parent process would normally forcibly terminate the child process anyway, so we only reach this point if the
94//parent process was terminated forcibly and didn't clean up after itself.
95Process::kill(Process::pid());