LoginSignup
3
2

More than 3 years have passed since last update.

PHPでプロセスIDを取得して、排他制御する方法をメモ

Posted at

管理画面でCSVファイル出力など、2度押し防止対策として使ってます。

//プロセスID取得
$pid = getmypid();

取得したプロセスIDを一時的にファイルに保存
タスク実行後に、ファイル削除

$file = "/tmp/pid.txt";

$fp = fopen($file,"w");
fwrite($fp,$pid);
fclose($fp);

//タスク実行

//ファイル削除
unlink($file);

タスクが実行中かどうかは、上記で生成したプロセスIDを格納したファイルを参照し、
そのプロセスIDが実行されているかどうかpsコマンドで確認するように書いてます。

$file = "/tmp/pid.txt";
if(file_exists($file)) {
    // ファイル内に記載されているプロセスIDを取得
    $pid = file_get_contents($file);

    //取得したプロセスIDが動いていないかチェック
    $cmd = "ps h " . $pid;
    exec($cmd, $output, $result);
}

PHPでプロセスIDを取得するのは初めてやりました〜

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2