<?php declare(strict_types=1);
namespace Inhere\Console\Examples\Controller;
use Inhere\Console\Controller;
use RuntimeException;
use Toolkit\Sys\ProcessUtil;
use Toolkit\Sys\Sys;
use function is_resource;
class ProcessController extends Controller
{
protected static $name = 'process';
protected static $description = 'Some simple process to create and use examples';
protected static function commandAliases(): array
{
return [
'cpr' => 'childProcess',
'mpr' => 'multiProcess',
'dr' => 'daemonRun',
'rs' => 'runScript',
'rb' => 'runInBackground',
];
}
public function runScriptCommand(): void
{
/*$script = '<?php echo "foo"; ?>';*/
$script = '<?php print_r($_SERVER); ?>';
$descriptorSpec = [
0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['file', $this->app->getRootPath() . '/examples/tmp/error-output.log', 'a'] ];
$process = proc_open('php', $descriptorSpec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], $script);
fclose($pipes[0]);
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$this->write("RESULT:\n" . $result);
$retVal = proc_close($process);
echo "command returned $retVal\n";
}
}
public function childProcessCommand(): void
{
$ret = ProcessUtil::create(function ($pid) {
echo "print in process $pid";
sleep(5);
});
if ($ret === false) {
$this->output->liteError('current env is not support process create.');
}
}
public function daemonRunCommand(): void
{
$ret = ProcessUtil::daemonRun(function ($pid) {
$this->output->info("will running background by new process: $pid");
});
if ($ret === 0) {
$this->output->liteError('current env is not support process create.');
}
}
public function runInBackgroundCommand(): void
{
$script = '<?php print_r($_SERVER); ?>';
$ret = Sys::execInBackground("php $script");
if ($ret === false) {
$this->output->liteError('current env is not support process create.');
}
}
public function multiProcessCommand(): void
{
}
}