是否可以检查特定进程是否正在睡眠或运行?

Raf*_*rsk 4 command-line bash process

我在 Ubuntu 上创建了以下可以暂停启动特定进程的脚本:

#!/bin/bash

loopProcess () {
   COUNTER=0
   while [  true ]; do
      echo $COUNTER
      sleep 1
      let COUNTER=COUNTER+1 
   done
}

loopProcess &
pidLoopProcess="$!"

while [  true ]; do
   read -p "" state
   if [ "$state" == 'a'  ]; then
      echo "Process is running"
      kill -CONT "$pidLoopProcess"
   elif [ "$state" == 'b'  ]; then
      echo "Process is sleeping"
      kill -STOP "$pidLoopProcess"
   fi  
done
Run Code Online (Sandbox Code Playgroud)

演示它是如何工作的:

在此处输入图片说明

我想知道是否可以使用命令行检查特定进程何时运行休眠。伪代码将是这样的:

if [ "$(StatePID $pidLoopProcess)" == 'sleeping'  ]; then
    ## do something
fi
Run Code Online (Sandbox Code Playgroud)

我知道使用这个脚本我可以声明一些全局变量并将它们用作标志......但我想知道是否有一个命令行工具可以为我做这件事。在那儿?是否可以?

ter*_*don 14

在 Linux 上,您可以使用它来获取具有给定 PID 的进程的状态:

ps -o stat= $pid
Run Code Online (Sandbox Code Playgroud)

T当进程停止时返回。因此,假设您使用的是 Linux 系统,您可以执行以下操作:

if [ "$(ps -o stat= $pid)" = "T" ]; then 
    echo stopped
else 
    echo not stopped
fi
Run Code Online (Sandbox Code Playgroud)

进程状态代码的完整列表在man ps

PROCESS STATE CODES
       Here are the different values that the s, stat and state output specifiers
       (header "STAT" or "S") will display to describe the state of a process:

               D    uninterruptible sleep (usually IO)
               I    Idle kernel thread
               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
Run Code Online (Sandbox Code Playgroud)