【问题标题】:How to check the path which has been a running process?如何检查已运行进程的路径?
【发布时间】:2014-09-25 11:54:50
【问题描述】:

一开始就为我的英语道歉。

我在服务器上有一个正在运行的进程,当我执行时:

ps -aux | grep script.sh

我得到这样的结果:

root     28104  0.0  0.0 106096  1220 pts/7    S+   08:27   0:00 /bin/bash ./script.sh

但是这个脚本是从例如运行的。 /home/user/my/program/script.sh

那么,如何获取脚本运行位置的完整路径?我有许多名称完全相同的脚本,但它们从不同的位置运行,我需要知道给定脚本的运行位置。

感谢回复!

【问题讨论】:

    标签: linux bash process path pid


    【解决方案1】:

    试试下面的脚本:

    for each in `pidof script.sh`
    do
       readlink /proc/$each/cwd
    done
    

    这将找到所有正在运行的 script.sh 脚本的 pid.s 并找到 /proc 对应的 cwd(当前工作目录)。

    【讨论】:

      【解决方案2】:

      使用密码 用法:pwdx pid ... (显示进程工作目录) 例如,

      pwdx 20102
      

      其中 20102 是 pid 这将显示进程的进程工作目录

      【讨论】:

        【解决方案3】:
        #!/bin/bash
        
        #declare the associative array with PID as key and process directory as value
        declare -A dirr
        
        #This will get the pid of the script
        pid_proc=($(ps -eaf | grep "$1.sh" | grep -v "grep" | awk '{print $2}'))
        
        
        for PID in ${pid_proc[@]}
        do
            #using Debasish method
            dirr[$PID]=$(pwdx $PID)
            # Below are different process to get the CWD of running process
            # using user1984289 method
            #dirr[$PID]=$(readlink /proc/"$PID"/cwd)
            #dirr[$PID]=$(cd /proc/$PID/cwd; /bin/pwd)
        done
        
        # iterate using the keys of the associative and get the working directory
        for PID in "${!dirr[@]}"
        do
         echo "The script '$1.sh' with PID:'$PID' is in the directory '${dirr[$PID]}'"
        done
        

        【讨论】:

          【解决方案4】:

          使用pgrep 获取实例的PID,然后读取关联的CWD 目录的链接。基本上,与@user1984289 相同的方法,但使用pgrep 而不是pidof,这与我系统上的bash 脚本名称不匹配(即使使用-x 选项):

          for pid in $(pgrep -f foo.sh); do readlink /proc/$pid/cwd; done
          

          只需将foo.sh 更改为您的脚本名称即可。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-17
            • 1970-01-01
            • 1970-01-01
            • 2015-05-29
            • 1970-01-01
            • 2011-02-12
            相关资源
            最近更新 更多