我在 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