/ /バックグラウンドで実行されているコマンドを検出します-exec、php

バックグラウンドで実行されているコマンドを検出する - exec、php

私はphpとそのコマンドラインインターフェースを使用していますスクリプトを実行します。スクリプトの実行中に、次のコードを使用して、バックグラウンドでいくつかのコマンドを呼び出します(そのうちのいくつかは非常に時間がかかります)。 php.net

function execInBackground($cmd) {
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}

すべてのコマンドが完全に実行される前に、メインスクリプトが数回呼び出される場合があります。

コマンドを実行する前に、スクリプトの前回の実行からすでにバックグラウンドで実行されているかどうかを確認する方法はありますか?

回答:

回答№1は1

背景を追跡できる1つの方法コマンドは、情報をファイルのどこかに保存することです。コマンドの名前はシステム全体で一意でない可能性があるため、確認できません。プロセスIDを構成ファイルに保存し、次の文字列でコマンドを確認できます。

function execInBackground($cmd)
{
$running = false;

// get the state of our commands
$state = json_decode(file_get_contents("state.json"));

// check if the command we want to run is already running and remove commands that have ended
for ($i = 0; $i < count($state->processes); $i++)
{
// check if the process is running by the PID
if (!file_exists("/proc/" . $state->processes[$i]->pid))
{
// this command is running already, so remove it from the list
unset($state->processes[$i]);
}

else if ($cmd === $state->processes[$i]->command)
{
$running = true;
}
}

// reorder our array since it"s probably out of order
$state->processes = array_values($state->processes);

// run the command silently if not already running
if (!$running)
{
$process = proc_open($cmd . " > /dev/null &", array(), $pipes);
$procStatus = proc_get_status($process);

$state->processes[] = array("command" => $cmd, "pid" => $procStatus["pid"]);
}

// save the new state of our commands
file_put_contents("state.json", json_encode($state));
}

構成ファイルは次のようになります。

{
"processes": [
{
"command": "missilecomm launch -v",
"pid": 42792
}
]
}

(私はJSONの「説得」ですが、任意の形式を使用できます;))

これはあなたが 時々 同じコマンド文字列を複数回実行したかった。

どのように execInBackground() 終了したコマンドをクリアします。Linuxでのみ機能します。 WindowsにプロセスIDが存在するかどうかを確認する別の方法を見つける必要があります。このコードはテストされていません。 proc_* 呼び出しも正しいです。