Terminal.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /**
  3. * Created by PhpStorm
  4. * User Julyssn
  5. * Date 2022/12/15 11:03
  6. */
  7. namespace easyTask;
  8. class Terminal
  9. {
  10. /**
  11. * @var object 对象实例
  12. */
  13. protected static $instance;
  14. protected $rootPath;
  15. /**
  16. * 命令执行输出文件
  17. */
  18. protected $outputFile = null;
  19. /**
  20. * proc_open 的参数
  21. */
  22. protected $descriptorsPec = [];
  23. protected $pipes = null;
  24. protected $procStatus = null;
  25. protected $runType = 1;
  26. protected $process = null;
  27. /**
  28. * @param int $runType 1 task使用 输出连续记录 2 普通使用 输出读取后删除
  29. * @return object|static
  30. */
  31. public static function instance($runType, $outputName = null)
  32. {
  33. if (is_null(self::$instance)) {
  34. self::$instance = new static($runType, $outputName);
  35. }
  36. return self::$instance;
  37. }
  38. public function __construct($runType, $outputName = null)
  39. {
  40. $this->rootPath = root_path();
  41. $this->runType = $runType;
  42. // 初始化日志文件
  43. if ($this->runType === 1) {
  44. $outputDir = Helper::getStdPath();
  45. $this->outputFile = $outputDir . 'exec_' . $outputName . '.std';
  46. } else {
  47. $outputDir = $this->rootPath . 'runtime' . DIRECTORY_SEPARATOR;
  48. $this->outputFile = $outputDir . 'exec_' . getOnlyToken() . '.log';
  49. file_put_contents($this->outputFile, '');
  50. }
  51. // 命令执行结果输出到文件而不是管道
  52. $this->descriptorsPec = [0 => ['pipe', 'r'], 1 => ['file', $this->outputFile, 'a'], 2 => ['file', $this->outputFile, 'a']];
  53. }
  54. public function __destruct()
  55. {
  56. // 类销毁 删除文件,type为2才删除
  57. if ($this->runType == 2) {
  58. unlink($this->outputFile);
  59. }
  60. }
  61. public function exec(string $command)
  62. {
  63. $this->process = proc_open($command, $this->descriptorsPec, $this->pipes, $this->rootPath);
  64. foreach ($this->pipes as $pipe) {
  65. fclose($pipe);
  66. }
  67. proc_close($this->process);
  68. if ($this->runType == 2) {
  69. $contents = file_get_contents($this->outputFile);
  70. return $contents;
  71. }
  72. }
  73. public function getProcStatus(): bool
  74. {
  75. $status = proc_get_status($this->process);
  76. return (bool)$status['running'];
  77. }
  78. }