macOS下如何在bash/zsh/sh中获取调用Shell脚本的qBittorrent的PID?
获取qBittorrent的PID(macOS环境)
我在macOS上使用qBittorrent,它支持下载完成后自动运行Shell脚本。现在需要在脚本里获取qBittorrent的PID,但直接用$PPID得到的是/sbin/launchd,推测qBittorrent是通过launchd调用脚本的。
已尝试的命令及结果:
- 执行
ps $PPID -o comm= >> /Users/john/Desktop/log.txt 2>&1,返回/sbin/launchd - 执行
ps -o comm= >> /Users/john/Desktop/log.txt 2>&1,返回多个/bin/zsh或-zsh进程(当时有4个终端窗口活跃)
需要解决的问题:如何在脚本中正确获取qBittorrent的PID?是否需要遍历父进程列表?具体实现方法是什么?
解决方案
方法1:直接通过进程名查找(最简单可靠)
qBittorrent的进程名固定为qBittorrent,直接用pgrep命令即可获取PID:
QB_PID=$(pgrep qBittorrent)
如果担心存在同名进程(一般不会),可以用更精确的过滤:
QB_PID=$(ps aux | grep -E '[q]Bittorrent' | awk '{print $2}')
这里[q]的写法是为了避免grep自身进程被匹配到。
方法2:遍历父进程链(追溯调用关系)
如果需要严格从脚本的调用链找到qBittorrent,可以编写循环逐级向上查询父进程:
current_pid=$$ while true; do parent_pid=$(ps -o ppid= -p $current_pid | tr -d ' ') parent_comm=$(ps -o comm= -p $parent_pid) if [[ "$parent_comm" == "qBittorrent" ]]; then QB_PID=$parent_pid break elif [[ "$parent_pid" == "1" ]]; then # 追到launchd(PID 1)仍未找到,用进程名查找兜底 QB_PID=$(pgrep qBittorrent) break fi current_pid=$parent_pid done echo "qBittorrent PID: $QB_PID"
这个脚本从当前脚本的PID($$)开始,逐层向上查找父进程,直到找到qBittorrent或追到系统进程launchd。
方法3:利用qBittorrent Web API(精准无歧义)
如果开启了qBittorrent的Web UI,可以通过API直接获取自身PID:
- 先在qBittorrent设置中开启Web UI,设置用户名和密码
- 脚本中调用API:
# 需要安装jq解析JSON QB_PID=$(curl -s -u "你的用户名:你的密码" http://localhost:8080/api/v2/app/version | jq -r '.pid')
如果没有安装jq,可用grep+sed替代:
QB_PID=$(curl -s -u "你的用户名:你的密码" http://localhost:8080/api/v2/app/version | grep -o '"pid":[0-9]*' | sed 's/"pid"://')
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

