列出在给定目录中运行的进程

问题描述

我正在处理一个应用程序,该应用程序会产生多个单独的进程,当礼貌地询问时,其中一些进程有时不会消失 - 通过使用应用程序自己的方式。

这意味着,他们必须被粗暴地驱逐(使用 SIGTERM),然后,对于特别顽固的人 - 残酷地(使用 SIGKILL)。

麻烦的是找到它们... 你如何列出所有进程,这些进程考虑给定目录——或其子目录——它的工作目录(cwd)?

我能想到的最好方法调用lsof -b -w -u $(whoami),然后解析最后一列以查找我的目录,然后通过 {{} 运行第二列(PID) 1}}。

也许还有更好的办法?

解决方法

如果只关心工作目录,可以使用awk来测试输出的第4列是否为cwd。而 awk 还可以检查最后一列,看看它是否在您关心的目录中。

procs=$(lsof -b -w -u $(whoami)  | awk '$4 == "cwd" && $NF ~ /^\/path\/to\/directory(\/|$)/ { print $2 }')

由于每个进程只有一个 cwd 引用,因此您无需使用 sort -u 删除重复项。

,

假设一个典型的 linux 环境,procfs 文件系统安装在 /proc

#!/usr/bin/env bash

# Script takes the desired directory as its argument and prints out
# all pids with that directory or a child directory as their working
# directory (As well as what the cwd is)

shopt -s extglob

dir=${1#/}

for p in /proc/[0-9]*; do
    cwd=$(readlink -m "$p/cwd")
    if [[ ${cwd#/} == $dir?(/*) ]]; then
       printf "%d\t%s\n" "${p#/proc/}" "$cwd"
    fi
done