developer's diary

最近はc#のエントリが多いです

phpで非同期処理

PHP で PIDファイルを利用する | Xlune::Blogを参考に作成

index.php

<?php

if(checkRunProcess("worker.pid")){
	echo "処理が終わっていません。";
}else{
	shell_exec('php worker.php > /dev/null 2>&1 &');
	echo "非同期処理を実行しました。";
}

//プロセスが生きてるかチェック(生きてる:true,死んでる:false)
function checkRunProcess($pid_file){
	if(file_exists($pid_file)){
		$_pid = trim(file_get_contents($pid_file));
		system("kill -s 0 {$_pid}", $_status);
		if($_status){
			unlink($pid_file);
			return false;
		}else{
			return true;
		}
	}
}


worker.php

<?php
//HTTP経由での起動時は処理を行わない
if($_SERVER['DOCUMENT_ROOT']){
exit(0);
}

$pid_file = "worker.pid";
if(checkRunProcess($pid_file)){
	echo "処理が終わっていません。";
	exit(0);
}else{
	system('echo '.getmypid().' > '.$pid_file, $_status);
	if($_status){
		die('ERROR: PIDファイルの作成に失敗しました。');
	}

	//主処理
	sleep(10);

	//pidファイルを削除
	unlink($pid_file);
}



//プロセスが生きてるかチェック(生きてる:true,死んでる:false)
function checkRunProcess($pid_file){
	if(file_exists($pid_file)){
		$_pid = trim(file_get_contents($pid_file));
		system("kill -s 0 {$_pid}", $_status);
		if($_status){
			unlink($pid_file);
			return false;
		}else{
			return true;
		}
	}
}


ブラウザからindex.phpにアクセスしてからコンソールでプロセスを確認

[...@localhost]$ ps aux | grep php
apache    3546  1.0  1.3  94424  6896 ?        S    23:55   0:00 php worker.php