PidManager.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace think\swoole;
  3. use Swoole\Process;
  4. class PidManager
  5. {
  6. /** @var string */
  7. protected $file;
  8. public function __construct(string $file)
  9. {
  10. $this->file = $file;
  11. }
  12. public function getPid()
  13. {
  14. if (is_readable($this->file)) {
  15. return (int) file_get_contents($this->file);
  16. }
  17. return 0;
  18. }
  19. /**
  20. * 是否运行中
  21. * @return bool
  22. */
  23. public function isRunning()
  24. {
  25. $pid = $this->getPid();
  26. return $pid > 0 && Process::kill($pid, 0);
  27. }
  28. /**
  29. * Kill process.
  30. *
  31. * @param int $sig
  32. * @param int $wait
  33. *
  34. * @return bool
  35. */
  36. public function killProcess($sig, $wait = 0)
  37. {
  38. $pid = $this->getPid();
  39. $pid > 0 && Process::kill($pid, $sig);
  40. if ($wait) {
  41. $start = time();
  42. do {
  43. if (!$this->isRunning()) {
  44. break;
  45. }
  46. usleep(100000);
  47. } while (time() < $start + $wait);
  48. }
  49. return $this->isRunning();
  50. }
  51. }