
本質的にブロックされるプロセスがあります。まず実行されます。 2番目のプロセスを実行するには、最初のプロセスをバックグラウンドに移動し、2番目のプロセスを実行します。 wait ステートメントを使用して端末で待機します。しかし、シェルを終了した後(CTRL+を押すC)、最初のプロセスがスムーズに終了しないようです。シェルスクリプトは次のとおりです。
実行.sh
#!/bin/sh
# start process one in background
python3 -m http.server 8086 &
# start second process
firefox "http://localhost:8086/index.html"
wait
同様の質問が見つかりましたここしかし、正しく動作しないようです。デフォルトでは、2 番目に電話すると、サーバーは./execute.sh
「アドレスがすでに使用中です」と言います。これは、サーバーが正常にシャットダウンできないことを意味します。一方、端末でサーバーを手動で実行すると、スムーズにシャットダウンします。
答え1
ctrl + cを押したときにプロセスが終了するように割り込みをキャプチャすることもできます。
#!/bin/sh
trap ctrl_c INT
ctrl_c () {
kill "$bpid"
exit
}
# start process one in background
python3 -m http.server 8086 &
bpid=$!
# start second process
firefox "http://localhost:8086/index.html"
wait
答え2
Firefoxが終了したら、Pythonプログラムを終了します。
私の頭の上から:
#!/bin/sh
# start process one in background
python3 -m http.server 8086 &
pid=$!
# start second process
firefox "http://localhost:8086/index.html"
kill "$!"
wait # wait for it to actually exit
# if it ignores SIGTERM, this'll hang
あるいは、スクリプトで開始されたFirefoxプロセスが実際にフォアグラウンドで実行されていないため、機能しませんfirefox
(ただし、既存のプロセスに新しいウィンドウを開くようにシグナルを送信することもできます)。
ただし、ユーザー入力を待つことができます。
#!/bin/sh
# start process one in background
python3 -m http.server 8086 &
pid=$!
# start second process
firefox "http://localhost:8086/index.html"
echo "Started Python HTTP server"
echo "Press enter to close it"
read tmp
echo "Asking the Python HTTP server to terminate"
kill "$!"
wait # wait for it to actually exit
# if it ignores SIGTERM, this'll hang
echo "Done."
別の解決策は、Python HTTPサーバーにアイドルタイマーを実装することです。 N分ごとに覚醒させ、最後の要求以降M分以上が過ぎたか確認し、そうであれば終了します。 Mを短くしないでください。そうでなければ、短い休憩を取ると死ぬでしょう。