Terminal.php 2.6 KB

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