【问题标题】:Linux: Reading the output of readlink /proc/pid/exe within a Bash ScriptLinux:在 Bash 脚本中读取 readlink /proc/pid/exe 的输出
【发布时间】:2015-06-01 13:49:59
【问题描述】:

所以我正在编写一个 bash 脚本,它将通过 /proc/[pid] 中的所有进程 ID 运行并读取用于运行它的可执行文件。

据我了解,/proc 文件系统包含 /proc/[pid]/exe 符号链接。在 bash 脚本中,我正在尝试研究如何读取“readlink /proc/[pid]/exe”的值以检查是否(已删除)或不返回任何内容以查明磁盘上是否存在原始可执行文件。

到目前为止,有没有办法做到这一点?

#!/bin/bash
pid = "0"

while [ $pid -lt 32769 ]
do
    if [-d /proc/$pid]; then
        if [-f /proc/$pid/exe]; then
            echo $pid
            readlink /proc/$pid/exe
        fi
    fi
    pid = $[$pid+1]
done

这不起作用并且总是什么都不返回。我正在尝试列出磁盘上不再有其可执行文件的所有进程。

【问题讨论】:

    标签: linux bash linux-kernel procfs


    【解决方案1】:

    这对你有用吗?

    #!/bin/bash
    
    for i in $(ls /proc | awk '/^[[:digit:]]+/{print $1}'); do
      if [ -h /proc/$i/exe ]; then
        echo -n "$i: "
        if readlink /proc/$i/exe >/dev/null 2>&1 ; then
          echo "executable exists"
        else
          echo "executable not found"
        fi
      fi
    done
    

    【讨论】:

    • 为什么不for i in /proc/[0-9]*/exe; do
    • 这对我有用,除了 for 循环。我终于使用了while循环。 '而 [ $pid -lt 32769 ]'。虽然此方法不适用于已删除的可执行文件。
    • 好,@caf!只是没有想到那个方法。 @DesiBoyz,出于好奇,for 循环出了什么问题?
    【解决方案2】:

    我已更新您的脚本以使其正常工作。请注意,-f 检查文件名是否代表 常规 文件。我会为符号链接返回 false:

    pid="0"
    while [ $pid -lt 32769 ]
    do
        if [ -d /proc/$pid ]; then
            if [ -h /proc/$pid/exe ]; then
                echo $pid
                readlink /proc/$pid/exe
            fi
        fi
        pid=$[$pid+1]
    done
    

    【讨论】:

    • 谢谢,OrenD,但这似乎不起作用。我在上面添加了更多细节。
    • 我已经用适合你的脚本版本更新了我的答案。
    • 你知道我在哪里可以找到诸如 -h、-f、-d 等的参考吗?我尝试搜索找不到任何参考资料。
    • 检查手册页中的“测试”命令以获取有关这些标志的信息。
    【解决方案3】:

    您可以通过打印 $? 来读取 shell 中任何命令后的返回值?变量:

     readlink
     echo $?
    

    如果链接无效,$?将大于 0。

    但是如果链接存在并且实际文件被删除,你可以使用类似的东西:

    ls `readlink somelink`
    

    【讨论】:

    • 我的错,我理解错了,我修改了答案!
    【解决方案4】:
       readlink -f `ls --dereference /proc/$pid/exe`
    

    【讨论】:

    • 一般来说,如果答案包含对代码的用途的解释,以及为什么在不介绍其他人的情况下解决问题的原因,答案会更有帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-03-15
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2017-12-22
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多