Linux shell - 如果文件已被删除,如何查找所有正在运行的进程

时间:2014-10-08 20:34:35

标签: linux bash shell

我想确定是否存在正在运行的进程(相关进程的文件)不再存在。

到目前为止,我有:

# [ ! -f /my/file ]; than echo "NOT exist!"; fi

了解文件是否存在

现在我需要从进程列表中提取生成进程的文件,删除参数,并验证文件是否存在...... 但我正努力让它发挥作用。 另外,我必须小心处理过程: / bin / sh /my/script.sh / usr / bin / python / my / python_file

(对于第二种情况,我可以部分识别是否已使用“lsof | grep deleted”删除了script.sh或python_file)

你知道是否有一种聪明的方法可以做到吗? 谢谢 DK

2 个答案:

答案 0 :(得分:2)

lsof将删除的文件列为/ path / to / file(已删除)

因此,作为root,这应该为您提供所有已删除文件的列表: lsof | grep'(已删除)'

之后,您可以通过将文件名与可执行文件名匹配来缩短列表(如果匹配,则可能是已删除的可执行文件正在运行)。

我还会匹配已知运行脚本的所有可执行文件(ruby,perl等)。更好的是,我宁愿过滤掉那些不会执行的可执行文件,并手动验证每个剩余的误报。

证明

编译这个小程序:

int
main(int argc, char *argv[]) {
    for ( ; ; ) {
    }

    return 0;
}

$ gcc useless.c -o useless

运行它

$ ./useless

然后删除它(在另一个终端):

$ rm useless

以root身份运行lsof:

useless     738             dioo  txt       REG                8,4       7955      40685 /home/dioo/useless (deleted)

答案 1 :(得分:0)

由于您使用的是Linux,我将通过/ proc

进行搜索
shopt -s extglob
for dir in /proc/+([0-9]); do
    # examine $dir/comm and decide if this is a script interpreter
    # like bash/python/perl ...

    # if yes, get the script name with
    my_script=$( cut -d '' -f 2 $dir/cmdline )

    # decide if the program or script file is missing
done