ManyPcntlInsertBigDataDepositCommand.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. class ManyPcntlInsertBigDataDepositCommand extends Command
  5. {
  6. /**
  7. * The name and signature of the console command.
  8. *
  9. * @var string
  10. */
  11. protected $signature = 'many_pcntl:insert_big_test_data';
  12. /**
  13. * The console command description.
  14. *
  15. * @var string
  16. */
  17. protected $description = '多进程插入测试数据';
  18. /**
  19. * Create a new command instance.
  20. *
  21. * @return void
  22. */
  23. public function __construct()
  24. {
  25. parent::__construct();
  26. }
  27. /**
  28. * Execute the console command.
  29. *
  30. * @return mixed
  31. */
  32. public function handle()
  33. {
  34. echo "Master process id = " . posix_getpid() . PHP_EOL;
  35. $i = 3;
  36. for ($i;$i>0;$i--){
  37. $pid = pcntl_fork();//创建一个新的进程
  38. switch ($pid) {
  39. case -1://如果为-1就代表失败
  40. die('Create failed');
  41. break;
  42. case 0://如果是0 就代表是子进程
  43. // Child
  44. echo "Child process id = " . posix_getpid() . PHP_EOL;//输出子进程的进程id
  45. $this->call('test:insert_big_data');
  46. sleep(2);
  47. echo "I will exit\n";
  48. break;
  49. default:
  50. // Parent
  51. if ($exit_id = pcntl_waitpid($pid, $status, WUNTRACED)) {//为了防止主进程挂了 子进程变成孤儿进程 所以在等待子进程执行完成以后
  52. echo "Child({$exit_id}) exited\n";
  53. }
  54. echo "Parent process id = " . posix_getpid() . PHP_EOL;
  55. break;
  56. }
  57. }
  58. }
  59. }