我正在 tmux 窗格中运行 python 程序。有时,python 进程会变成僵尸进程,我需要使用它的 pid 来杀死它。然而,这个命令
tmux list-panes -F '#{pane_active} #{pane_pid}'
仅提供窗格内bash的pid,无法将其杀死。那么如何获取python进程的pid呢?
我遇到了同样的问题,但我发现最好的解决方案是编写一个 bash 脚本,该脚本使用 tmux 提供的
tty
输入可以获取所有进程 PID。
文件是
getpaneprocessid.sh
#!/bin/bash
# Check for input parameter
if [[ -z "$1" ]]; then
echo "Usage: ./getpaneprocessid.sh <pane name> <show PID tree> <socket file name>"
echo "Where <pane name> is required, and the others are optional"
exit 1
fi
# Get param
panName="$1"
outputTree="$2"
tmuxCallback="$3"
if [ "$outputTree" = '' ]; then
outputTree=false
fi
# Get tty
if [ "$tmuxCallback" = '' ]; then
sessions=$(tmux list-s -F "#{session_name} #{pane_tty}" | grep "^$panName " 2>/dev/null)
else
sessions=$(tmux -S "$tmuxCallback" list-s -F "#{session_name} #{pane_tty}" | grep "^$panName " 2>/dev/null)
fi
if [ "$?" -ne "0" ]; then
echo "No running tmux sessions detected."
exit 1
fi
# Extract TTY
tty=$(echo "$sessions" | awk '{print $2}')
# Extract process IDs from tty
itemIndex=0
for p in $(ps -o pid -t "$tty" |tail -n +2)
do
process="$(awk -v PID=$p '{print PID}' /proc/$p/stat 2>/dev/null awk '{print $2}')"
if [[ $counter -eq "0" ]]; then
result=$(printf "%s%s" "$result" "$process")
else
result=$(printf "%s\n%s" "$result" "$process")
fi
((counter++))
done
if [ "$outputTree" = "true" ]; then
echo "$result"
else
echo "$result" | tail -1
fi
exit 1
这将获取所提供的 tmux 会话的进程 tre 的 PID,您所需要做的就是提供 tmux 会话名称,您可以使用
tmux ls
查看该名称。
对于本次演示,我运行了以下会话结构
bash
|-bash
|---top
其中 tmux 会话被称为
test
。
我可以运行以下命令
./getpaneprocessid.sh test
它又回来了
273278
但是通过运行
./getpaneprocessid.sh test true
,它会返回
232363
273208
273278
对应于我上面写的进程树 PID。
我可以使用以下命令确认这一点:
pstree -p 232363
返回:
bash(232363)───bash(273208)───top(273278)