-1

我想知道您是否有任何脚本可以获取正在休眠的进程的 PID (S) 并自动重新启动它

restart_pid() {
# First we need to find the program's arguments
SAVED_COMMAND="$(while IFS= read -r -d $'\0' f; do printf '%q ' "$f"; done < /proc/$1/cmdline)"
# Then we need to cd into its directory so that we stay as true to the intial conditions as possible
cd /proc/$1/cwd
# Now kill the process
kill $1
# Now we can restart the process
eval $SAVED_COMMAND
}
ps -ef
Zoho 3
htop
restart_pid 23924
kill -HUP 23924

我使用脚本通过 PID 重新启动进程,但每次我都需要在脚本中传递 PID。有什么办法可以自动化吗?

4

1 回答 1

0

ps 可以向您显示进程 ID 及其当前状态的列表:

ps -eo stat -o pid -o comm

从 ps 手册页中获取有关状态代码的更多信息:

进程状态代码 以下是 s、stat 和状态输出说明符(标题“STAT”或“S”)将显示以描述进程状态的不同值:

           D    uninterruptible sleep (usually IO)
           R    running or runnable (on run queue)
           S    interruptible sleep (waiting for an event to complete)
           T    stopped by job control signal
           t    stopped by debugger during the tracing
           W    paging (not valid since the 2.6.xx kernel)
           X    dead (should never be seen)
           Z    defunct ("zombie") process, terminated but not reaped by
                its parent

   For BSD formats and when the stat keyword is used, additional
   characters may be displayed:

           <    high-priority (not nice to other users)
           N    low-priority (nice to other users)
           L    has pages locked into memory (for real-time and custom IO)
           s    is a session leader
           l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads
                do)
           +    is in the foreground process group

ps 命令无疑需要根据进程名称 (comm) 进一步完善,这可以通过 awk 完成。例如,寻找名为“myapp”的进程

ps -eo stat -o pid | awk '$1=="S" && $3=="myapp" { print $2 }'

检查进程状态(第一个空格分隔的字段)是否为 S,进程名称(第三个空格分隔的字段)是否等于 myapp。最后,假设进程符合预期(重要步骤),这可以与您的重新启动脚本集成,以利用 awk 的系统函数重新启动所有进程:

ps -eo stat -o pid | awk '$1=="S" { system("./restartscript "$2) }'
 
于 2020-12-07T15:19:51.997 回答