如何在 Unix / Linux 中获取进程的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/606041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the path of a process in Unix / Linux
提问by lsalamon
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?
或者在这些环境中是否有其他方法可以做到这一点?
采纳答案by jpalecek
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 上,符号链接/proc/<pid>/exe
具有可执行文件的路径。使用命令readlink -f /proc/<pid>/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 <actual path to binary>
和cksum /proc/<pid>/object/a.out
。
回答by hyperboreean
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,然后将其与路径连接/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
回答by Vatine
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().
第 1 步是检查 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]中获取程序名称,然后从环境中获取用户的PATH并通过它看看是否有合适的具有相同名称的可执行二进制文件。
Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.
请注意,argv[0] 是由执行程序的进程设置的,因此它不是 100% 可靠的。
回答by Hiperion
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 */
size_t buff_len;
if (buff_len = readlink ("/proc/self/exe", path, dest_len - 1) != -1)
{
path [buff_len] = '#!/bin/bash
# @author Lukas Gottschall
PID=`ps aux | grep precessname | grep -v grep | awk '{ print }'`
PATH=`ls -ald --color=never /proc/$PID/exe | awk '{ print }'`
echo $PATH
';
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:Fixed the bug reported by Mark lakata.
编辑:修复了 Mark lakata 报告的错误。
回答by DwD
Find the path to a process name
查找进程名称的路径
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);
回答by Jimmio92
You can also get the path on GNU/Linux with (not thoroughly tested):
您还可以使用(未经彻底测试)获取 GNU/Linux 上的路径:
*strrchr(buf, '/') = 'ps -ef | grep 786
';
/*chdir(buf);*/
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 /:
如果您希望可执行文件的目录可能将工作目录更改为进程目录(用于媒体/数据/等),则需要删除最后一个 / 之后的所有内容:
getPathByPid()
{
if [[ -e /proc//object/a.out ]]; then
inode=`ls -i /proc//object/a.out 2>/dev/null | awk '{print }'`
if [[ $? -eq 0 ]]; then
strnode=${inode}"$"
strNum=`ls -li /proc//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 }'`
n2=`echo $strNum|awk -F"." '{print }'`
# 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
}
回答by hahakubile
You can find the exe easily by these ways, just try it yourself.
你可以通过这些方式轻松找到exe,自己试试吧。
ll /proc/<PID>/exe
pwdx <PID>
lsof -p <PID> | grep cwd
ll /proc/<PID>/exe
pwdx <PID>
lsof -p <PID> | grep cwd
回答by User
I use:
我用:
##代码##Replace 786 with your PID or process name.
将 786 替换为您的 PID 或进程名称。
回答by gobi
pwdx <process id>
pwdx <process id>
This command will fetch the process path from where it is executing.
此命令将从执行的位置获取进程路径。