PHP進程間通訊-訊號

  • 2019 年 11 月 10 日
  • 筆記

訊號

訊號是一種系統調用。通常我們用的kill命令就是發送某個訊號給某個進程的。具體有哪些訊號可以在liunx/mac中運行 kill -l 查看。下面這個例子中,父進程等待5秒鐘,向子進程發送sigint訊號。子進程捕獲訊號,調訊號處理函數處理。

程式碼演示

<?php  $childList = [];  $parentId = posix_getpid();    //訊號處理函數  function signHandler($sign){      $pid = posix_getpid();      exit("process:{$pid},is killed,signal is {$sign}n");  }    $pid = pcntl_fork();  if ($pid == -1){      // 創建子進程失敗      exit("fork fail,exit!n");  }elseif ($pid == 0){      //子進程執行程式      //註冊訊號處理函數      declare(ticks = 10);      pcntl_signal(SIGINT,"signHandler");//註冊SIGINT訊號處理函數      $pid = posix_getpid();      while (true){          echo "child process {$pid},is running.......n";          sleep(1);      }  }else{      $childList[$pid] = 1;      sleep(5);      posix_kill($pid,SIGINT);//向指定進程發送一個訊號  }    // 等待子進程結束  while(!empty($childList)){      $pid = pcntl_wait($status);      if ($pid > 0){          unset($childList[$pid]);      }  }    echo "The child process is killed by parent process {$parentId}n";

運行結果

當父進程沒有發送訊號的時候,子進程會一直循環輸出『child process is running…』,父進程發送訊號後,子進程在檢查到有訊號進來的時候調用對應的回調函數處理退出了子進程。

declare(ticks = 10)

這裡的ticks=10,可以理解為程式執行10條低級語句後,檢查看有沒有未執行的訊號,有的話就去處理。

關於 declare(ticks = n) 的詳細講解可以參考 (https://my.oschina.net/Jacker/blog/32936)