首页 文章

如何在Unix / Linux中获取进程的路径

提问于
浏览
111

在Windows环境中,有一个API来获取正在运行进程的路径 . Unix / Linux中有类似的东西吗?

或者在这些环境中还有其他方法吗?

10 回答

  • 2

    在Linux上,符号链接 /proc/<pid>/exe 具有可执行文件的路径 . 使用命令 readlink -f /proc/<pid>/exe 获取值 .

    在AIX上,此文件不存在 . 你可以比较 cksum <actual path to binary>cksum /proc/<pid>/object/a.out .

  • -1

    你可以通过这些方式轻松找到exe,只需自己尝试一下 .

    • ll /proc/<PID>/exe

    • pwdx <PID>

    • lsof -p <PID> | grep cwd

  • 1

    有点晚了,但所有的答案都是针对linux的 .

    如果你还需要unix,那么你需要这个:

    char * getExecPath (char * path,size_t dest_len, char * argv0)
    {
        char * baseName = NULL;
        char * systemPath = NULL;
        char * candidateDir = NULL;
    
        /* the easiest case: we are in linux */
        size_t buff_len;
        if (buff_len = readlink ("/proc/self/exe", path, dest_len - 1) != -1)
        {
            path [buff_len] = '\0';
            dirname (path);
            strcat  (path, "/");
            return path;
        }
    
        /* Ups... not in linux, no  guarantee */
    
        /* check if we have something like execve("foobar", NULL, NULL) */
        if (argv0 == NULL)
        {
            /* we surrender and give current path instead */
            if (getcwd (path, dest_len) == NULL) return NULL;
            strcat  (path, "/");
            return path;
        }
    
    
        /* argv[0] */
        /* if dest_len < PATH_MAX may cause buffer overflow */
        if ((realpath (argv0, path)) && (!access (path, F_OK)))
        {
            dirname (path);
            strcat  (path, "/");
            return path;
        }
    
        /* Current path */
        baseName = basename (argv0);
        if (getcwd (path, dest_len - strlen (baseName) - 1) == NULL)
            return NULL;
    
        strcat (path, "/");
        strcat (path, baseName);
        if (access (path, F_OK) == 0)
        {
            dirname (path);
            strcat  (path, "/");
            return path;
        }
    
        /* Try the PATH. */
        systemPath = getenv ("PATH");
        if (systemPath != NULL)
        {
            dest_len--;
            systemPath = strdup (systemPath);
            for (candidateDir = strtok (systemPath, ":"); candidateDir != NULL; candidateDir = strtok (NULL, ":"))
            {
                strncpy (path, candidateDir, dest_len);
                strncat (path, "/", dest_len);
                strncat (path, baseName, dest_len);
    
                if (access(path, F_OK) == 0)
                {
                    free (systemPath);
                    dirname (path);
                    strcat  (path, "/");
                    return path;
                }
            }
            free(systemPath);
            dest_len++;
        }
    
        /* again someone has use execve: we dont knowe the executable name; we surrender and give instead current path */
        if (getcwd (path, dest_len - 1) == NULL) return NULL;
        strcat  (path, "/");
        return path;
    }
    

    EDITED: 修正了Mark lakata报告的错误 .

  • 11

    我用:

    ps -ef | grep 786
    

    将786替换为您的PID或进程名称 .

  • 145

    在Linux中,每个进程在 /proc 中都有自己的文件夹 . 因此,您可以使用 getpid() 获取正在运行的进程的pid,然后将其与路径 /proc 连接,以获取您希望需要的文件夹 .

    这是Python中的一个简短示例:

    import os
    print os.path.join('/proc', str(os.getpid()))
    

    这是ANSI C中的示例:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/types.h>
    
    
    int
    main(int argc, char **argv)
    {
        pid_t pid = getpid();
    
        fprintf(stdout, "Path to current process: '/proc/%d/'\n", (int)pid);
    
        return EXIT_SUCCESS;
    }
    

    编译它:

    gcc -Wall -Werror -g -ansi -pedantic process_path.c -oprocess_path
    
  • 2

    pwdx <process id>

    此命令将从执行位置获取进程路径 .

  • 4

    没有“保证随时随地工作”的方法 .

    第1步是检查argv [0],如果程序是以其完整路径启动的,那么(通常)会有完整的路径 . 如果它是由相对路径启动的,那么同样如此(尽管这需要使用getcwd()获取当前工作目录 .

    如果以上都不成立,步骤2是获取程序的名称,然后从argv [0]获取程序的名称,然后从环境中获取用户的PATH并通过它查看是否有合适的具有相同名称的可执行二进制

    请注意,argv [0]由执行程序的进程设置,因此它不是100%可靠 .

  • 4

    谢谢:Kiwy
    使用AIX:

    getPathByPid()
    {
        if [[ -e /proc/$1/object/a.out ]]; then
            inode=`ls -i /proc/$1/object/a.out 2>/dev/null | awk '{print $1}'`
            if [[ $? -eq 0 ]]; then
                strnode=${inode}"$"
                strNum=`ls -li /proc/$1/object/ 2>/dev/null | grep $strnode | awk '{print $NF}' | grep "[0-9]\{1,\}\.[0-9]\{1,\}\."`
                if [[ $? -eq 0 ]]; then
                    # jfs2.10.6.5869
                    n1=`echo $strNum|awk -F"." '{print $2}'`
                    n2=`echo $strNum|awk -F"." '{print $3}'`
                    # brw-rw----    1 root     system       10,  6 Aug 23 2013  hd9var
                    strexp="^b.*"$n1,"[[:space:]]\{1,\}"$n2"[[:space:]]\{1,\}.*$"   # "^b.*10, \{1,\}5 \{1,\}.*$"
                    strdf=`ls -l /dev/ | grep $strexp | awk '{print $NF}'`
                    if [[ $? -eq 0 ]]; then
                        strMpath=`df | grep $strdf | awk '{print $NF}'`
                        if [[ $? -eq 0 ]]; then
                            find $strMpath -inum $inode 2>/dev/null
                            if [[ $? -eq 0 ]]; then
                                return 0
                            fi
                        fi
                    fi
                fi
            fi
        fi
        return 1
    }
    
  • 38

    您还可以使用(未经过全面测试)获取GNU / Linux上的路径:

    char file[32];
    char buf[64];
    pid_t pid = getpid();
    sprintf(file, "/proc/%i/cmdline", pid);
    FILE *f = fopen(file, "r");
    fgets(buf, 64, f);
    fclose(f);
    

    如果您希望可执行文件的目录可能将工作目录更改为进程的目录(对于媒体/数据/等),则需要删除最后一个/之后的所有内容:

    *strrchr(buf, '/') = '\0';
    /*chdir(buf);*/
    
  • 27

    找到进程名称的路径

    #!/bin/bash
    # @author Lukas Gottschall
    PID=`ps aux | grep precessname | grep -v grep | awk '{ print $2 }'`
    PATH=`ls -ald --color=never /proc/$PID/exe | awk '{ print $10 }'`
    echo $PATH
    

相关问题