【问题标题】:Script to restart the PID automatically自动重启 PID 的脚本
【发布时间】:2020-12-07 14:41:44
【问题描述】:

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

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。 有什么办法可以自动化吗?

【问题讨论】:

  • 可能有很多进程处于休眠状态?
  • 有时机器没有完成这个过程并且已经执行了另一个。因此,我需要获取休眠进程的 PID 并自动重新启动它们。休眠进程消耗大量 CPU。
  • "休眠进程消耗大量 CPU"?休眠进程不应消耗任何明显的 CPU。
  • 是的,但是在重新启动运行了200多个小时的“S”状态的进程的PID时,我释放了一个CPU。那么,我想知道是否可以自动重启处于“R”和“S”状态的进程?

标签: bash shell pid htop


【解决方案1】:

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

ps -eo stat -o pid -o comm

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

过程状态代码 以下是 s、stat 和 state 输出的不同值 说明符(标题“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) }'
 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 2010-12-17
    • 1970-01-01
    相关资源
    最近更新 更多