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

时间:2021-08-08 23:22:37

In Windows environment there is an API to obtain the path which is running a process. Is there something similar in Unix / Linux?

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

Or is there some other way to do that in these environments?

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

10 个解决方案

#1


132  

On Linux, the symlink /proc/<pid>/exe has the path of the executable. Use the command readlink -f /proc/<pid>/exe to get the value.

在Linux上,symlink /proc/ /exe具有可执行文件的路径。使用命令readlink -f /proc/ /exe获取值。

On AIX, this file does not exist. You could compare cksum <actual path to binary> and cksum /proc/<pid>/object/a.out.

在AIX上,这个文件不存在。您可以比较cksum <实际路径到二进制> 和cksum /proc/ /object/a.out。

#2


30  

You can find the exe easily by these ways, just try it yourself.

你可以通过这些方法轻松找到exe,你可以自己尝试一下。

  • ll /proc/<PID>/exe
  • /proc/< PID > / exe
  • pwdx <PID>
  • pwdx < PID >
  • lsof -p <PID> | grep cwd
  • lsof -p | grep cwd

#3


26  

EDITORS NOTE The code below has a bug. readlink does not null terminate the output string, so if it works, it was an accident.

编辑注意到下面的代码有一个错误。readlink不为空终止输出字符串,因此如果它工作,这是一个意外。

A little bit late, but all the answers were specific to linux.

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

If you need also unix, then you need this:

如果您还需要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 */
    if (readlink ("/proc/self/exe", path, dest_len) != -1)
    {
        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;
}

#4


9  

I use:

我使用:

ps -ef | grep 786

Replace 786 with your PID or process name.

用PID或进程名替换786。

#5


4  

In Linux every process has its own folder in /proc. So you could use getpid() to get the pid of the running process and then join it with the path /proc to get the folder you hopefully need.

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

Here's a short example in Python:

下面是Python的一个简短示例:

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

Here's the example in ANSI C as well:

这里还有一个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;
}

Compile it with:

编译:

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

#6


2  

There's no "guaranteed to work anywhere" method.

没有“保证在任何地方工作”的方法。

Step 1 is to check argv[0], if the program was started by its full path, this would (usually) have the full path. If it was started by a relative path, the same holds (though this requires getting teh current working directory, using getcwd().

第一步是检查argv[0],如果程序是由它的完整路径启动的,那么它(通常)将拥有完整的路径。如果它是由一个相对路径启动的,则保持不变(尽管这需要使用getcwd()获取当前工作目录。

Step 2, if none of the above holds, is to get the name of the program, then get the name of the program from argv[0], then get the user's PATH from the environment and go through that to see if there's a suitable executable binary with the same name.

第2步,如果上面这些都不成立,那么获取程序的名称,然后从argv[0]获取程序的名称,然后从环境中获取用户的路径,然后遍历该路径,看看是否有一个合适的、同名的可执行二进制文件。

Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.

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

#7


2  

thanks : Kiwy
with AIX:

谢谢: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
}

#8


2  

pwdx <process id>

pwdx <进程id>

This command will fetch the process path from where it is executing.

该命令将从正在执行的地方获取进程路径。

#9


1  

You can also get the path on GNU/Linux with (not thoroughly tested):

您还可以使用(未经过彻底测试)的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);

If you want the directory of the executable for perhaps changing the working directory to the process's directory (for media/data/etc), you need to drop everything after the last /:

如果您想要可执行文件的目录将工作目录更改为进程的目录(用于媒体/数据/等),您需要在最后/:

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

#10


-1  

Find the path to a process name

找到进程名的路径

#!/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

#1


132  

On Linux, the symlink /proc/<pid>/exe has the path of the executable. Use the command readlink -f /proc/<pid>/exe to get the value.

在Linux上,symlink /proc/ /exe具有可执行文件的路径。使用命令readlink -f /proc/ /exe获取值。

On AIX, this file does not exist. You could compare cksum <actual path to binary> and cksum /proc/<pid>/object/a.out.

在AIX上,这个文件不存在。您可以比较cksum <实际路径到二进制> 和cksum /proc/ /object/a.out。

#2


30  

You can find the exe easily by these ways, just try it yourself.

你可以通过这些方法轻松找到exe,你可以自己尝试一下。

  • ll /proc/<PID>/exe
  • /proc/< PID > / exe
  • pwdx <PID>
  • pwdx < PID >
  • lsof -p <PID> | grep cwd
  • lsof -p | grep cwd

#3


26  

EDITORS NOTE The code below has a bug. readlink does not null terminate the output string, so if it works, it was an accident.

编辑注意到下面的代码有一个错误。readlink不为空终止输出字符串,因此如果它工作,这是一个意外。

A little bit late, but all the answers were specific to linux.

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

If you need also unix, then you need this:

如果您还需要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 */
    if (readlink ("/proc/self/exe", path, dest_len) != -1)
    {
        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;
}

#4


9  

I use:

我使用:

ps -ef | grep 786

Replace 786 with your PID or process name.

用PID或进程名替换786。

#5


4  

In Linux every process has its own folder in /proc. So you could use getpid() to get the pid of the running process and then join it with the path /proc to get the folder you hopefully need.

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

Here's a short example in Python:

下面是Python的一个简短示例:

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

Here's the example in ANSI C as well:

这里还有一个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;
}

Compile it with:

编译:

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

#6


2  

There's no "guaranteed to work anywhere" method.

没有“保证在任何地方工作”的方法。

Step 1 is to check argv[0], if the program was started by its full path, this would (usually) have the full path. If it was started by a relative path, the same holds (though this requires getting teh current working directory, using getcwd().

第一步是检查argv[0],如果程序是由它的完整路径启动的,那么它(通常)将拥有完整的路径。如果它是由一个相对路径启动的,则保持不变(尽管这需要使用getcwd()获取当前工作目录。

Step 2, if none of the above holds, is to get the name of the program, then get the name of the program from argv[0], then get the user's PATH from the environment and go through that to see if there's a suitable executable binary with the same name.

第2步,如果上面这些都不成立,那么获取程序的名称,然后从argv[0]获取程序的名称,然后从环境中获取用户的路径,然后遍历该路径,看看是否有一个合适的、同名的可执行二进制文件。

Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.

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

#7


2  

thanks : Kiwy
with AIX:

谢谢: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
}

#8


2  

pwdx <process id>

pwdx <进程id>

This command will fetch the process path from where it is executing.

该命令将从正在执行的地方获取进程路径。

#9


1  

You can also get the path on GNU/Linux with (not thoroughly tested):

您还可以使用(未经过彻底测试)的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);

If you want the directory of the executable for perhaps changing the working directory to the process's directory (for media/data/etc), you need to drop everything after the last /:

如果您想要可执行文件的目录将工作目录更改为进程的目录(用于媒体/数据/等),您需要在最后/:

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

#10


-1  

Find the path to a process name

找到进程名的路径

#!/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