Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Unix/Linux中获取进程的路径_Linux_Unix_Process_Path_Environment - Fatal编程技术网

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

如何在Unix/Linux中获取进程的路径,linux,unix,process,path,environment,Linux,Unix,Process,Path,Environment,在Windows环境中,有一个API来获取运行进程的路径。Unix/Linux中有类似的东西吗 或者在这些环境中是否有其他方法可以做到这一点?在Linux上,symlink/proc//exe具有可执行文件的路径。使用命令readlink-f/proc//exe获取值 在AIX上,此文件不存在。您可以比较cksum和cksum/proc//object/a.out在Linux中,每个进程在/proc中都有自己的文件夹。因此,您可以使用getpid()获取正在运行的进程的pid,然后将其与路径/p

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


或者在这些环境中是否有其他方法可以做到这一点?

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


在AIX上,此文件不存在。您可以比较
cksum
cksum/proc//object/a.out
在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;
}
没有“保证在任何地方都能工作”的方法

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

第2步,如果上述任何一项都不成立,则获取程序名,然后从argv[0]获取程序名,然后从环境中获取用户路径,并查看是否存在具有相同名称的合适可执行二进制文件


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

有点晚,但所有答案都是针对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;
}
char*getExecPath(char*path,size\t dest\u len,char*argv0)
{
char*baseName=NULL;
char*systemPath=NULL;
char*candidateDir=NULL;
/*最简单的情况是:我们使用linux*/
大小为浅黄色;
如果(buff_len=readlink(“/proc/self/exe”,路径,dest_len-1)!=-1)
{
路径[buff_len]='\0';
目录名(路径);
strcat(路径“/”;
返回路径;
}
/*Ups…不在linux中,不保证*/
/*检查是否有类似execve(“foobar”,NULL,NULL)的内容*/
如果(argv0==NULL)
{
/*我们投降,而放弃当前的道路*/
if(getcwd(path,dest_len)==NULL)返回NULL;
strcat(路径“/”;
返回路径;
}
/*argv[0]*/
/*如果dest_len

已编辑:修复了Mark lakata报告的错误。

查找进程名称的路径

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

您还可以在GNU/Linux上使用(未完全测试)获取路径:

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

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

你可以通过这些方法很容易地找到exe,你自己试试就可以了

  • ll/proc//exe
  • pwdx
  • lsof-p | grep-cwd
我使用:

ps -ef | grep 786
将786替换为您的PID或流程名称。

谢谢:
对于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
}
pwdx


此命令将从其执行的位置获取进程路径。

下面的命令在正在运行的进程列表中搜索进程名称,并将pid重定向到pwdx命令以查找进程的位置

ps -ef | grep "abc" |grep -v grep| awk '{print $2}' | xargs pwdx
用您的特定图案替换“abc”

或者,如果您可以将它配置为.bashrc中的一个函数,如果您需要经常使用它,您可能会发现它非常方便

ps1() { ps -ef | grep "$1" |grep -v grep| awk '{print $2}' | xargs pwdx; }
例如:

[admin@myserver:/home2/Avro/AvroGen]$ ps1 nifi

18404: /home2/Avro/NIFI

希望这有助于某些人….

在Ubuntu最新版本上的Python输出:>>>>导入os>>>打印os.path.join('/proc',str(os.getpid()))/proc/24346请解释您的代码。如果您从其他地方复制并粘贴它,请链接到源代码。这段效率不高的代码所做的是获取进程名称(本质上是“PID”行是对
pgrep
)的替换;在下一行中,它获取正在执行的二进制文件的路径(
/proc/$PID/exe
是指向可执行文件的符号链接);最后它回显了该符号链接。感谢您共享Hiperion,但我需要指定一个PID并获取其exe路径,使用此代码可以吗?@Noitidart-将
“/proc/self/exe”
替换为
sprintf(foo,“/proc/%d/exe”,PID)
请注意,readlink不为null终止结果,因此此代码具有未定义的行为。
sudo
如果输出为空,则某些进程由其他系统用户创建。问题是关于获取信息的API,但无论如何还是要感谢。这太棒了。我知道
ps1() { ps -ef | grep "$1" |grep -v grep| awk '{print $2}' | xargs pwdx; }
[admin@myserver:/home2/Avro/AvroGen]$ ps1 nifi

18404: /home2/Avro/NIFI