特定のプロセスがスリープモードか実行中かを確認できますか?

特定のプロセスがスリープモードか実行中かを確認できますか?

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

どのように動作するかを示します。

ここに画像の説明を入力してください。

特定のプロセスがいつ実行されるかを確認できるかどうかを知りたいです。走るまたは眠るコマンドラインを使用してください。擬似コードは次のとおりです。

if [ "$(StatePID $pidLoopProcess)" == 'sleeping'  ]; then
    ## do something
fi

私はこのスクリプトを使用していくつかのグローバル変数を宣言し、それをフラグとして使用できることを知っています...しかしこれを行うためのコマンドラインツールがあるかどうか疑問に思います。あなたはいますか?可能ですか?

ベストアンサー1

Linuxでは、これを使用して特定のPIDを持つプロセスの状態を取得できます。

ps -o stat= $pid

Tプロセスが停止すると返されます。したがって、Linuxシステムを使用していると仮定すると、次のことができます。

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

プロセスステータスコードの完全なリストは次のとおりです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

おすすめ記事