PHPでシェルスクリプトを非同期で実行する方法は何ですか。
PHPでは、exec()関数を使用してシェルスクリプトを実行することができます。ただし、exec()関数は同期的であり、つまり、シェルスクリプトの実行が完了するまでPHPスクリプトは待ち続けます。シェルスクリプトを非同期で実行したい場合は、次の方法を使用できます:
- 実行する()
- 高校生の時、私はバスケットボールチームの一員でした。
exec("your_script.sh > /dev/null 2>&1 &");
ここでの> /dev/null 2>&1はスクリプトの出力を空のデバイスにリダイレクトすることを意味し、&記号はスクリプトをバックグラウンドで実行することを示しています。
- シェルを実行します。
- nohup を日本語で言うと、バックグラウンドで実行する際に使用するコマンドです。
shell_exec("nohup your_script.sh > /dev/null 2>&1 &");
Nohupコマンドは、HUP(ハングアップ)シグナルを無視し、スクリプトをバックグラウンドで実行します。
- プロセスを開始する方法
- stream_set_blocking()を使う
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open("your_script.sh", $descriptorspec, $pipes);
// 设置为非阻塞模式
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
// 关闭不需要的管道
fclose($pipes[0]);
// 获取脚本的输出
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
// 关闭管道和进程
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
PHPでシェルスクリプトを非同期で実行する方法についていくつか紹介しましたが、実際の要件に応じて適切な方法を選択してください。