編寫一個Linux進程守護腳本的大致步驟如下:
#!/bin/bash
process_name="your_process_name"
process_path="your_process_path"
check_process() {
local pid=$(pgrep -f $process_name)
if [[ -n "$pid" ]]; then
return 0
else
return 1
fi
}
start_process() {
$process_path &
}
stop_process() {
local pid=$(pgrep -f $process_name)
if [[ -n "$pid" ]]; then
kill -9 $pid
fi
}
while true; do
if ! check_process; then
start_process
fi
sleep 5
done
stop_process
完整的腳本示例:
#!/bin/bash
process_name="your_process_name"
process_path="your_process_path"
check_process() {
local pid=$(pgrep -f $process_name)
if [[ -n "$pid" ]]; then
return 0
else
return 1
fi
}
start_process() {
$process_path &
}
stop_process() {
local pid=$(pgrep -f $process_name)
if [[ -n "$pid" ]]; then
kill -9 $pid
fi
}
while true; do
if ! check_process; then
start_process
fi
sleep 5
done
stop_process
請根據實際情況修改process_name和process_path變量,然后保存腳本并設置為可執行文件(chmod +x daemon.sh)。