나는 어떻게 얻는 경로의 과정에서 Unix/Linux
-
03-07-2019 - |
문제
Windows 환경이 있을 얻을 수 있는 API 를 이 경로로 실행되는 프로세스입니다.가 비슷한에서 Unix/Linux?
또는 다른 방법으로 하는 이러한 환경에서는?
해결책
Linux, Symlink /proc/<pid>/exe
실행 파일의 경로가 있습니다. 명령을 사용하십시오 readlink -f /proc/<pid>/exe
가치를 얻으려면.
AIX에는이 파일이 존재하지 않습니다. 당신은 비교할 수 있습니다 cksum <actual path to binary>
그리고 cksum /proc/<pid>/object/a.out
.
다른 팁
이러한 방식으로 Exe를 쉽게 찾을 수 있습니다. 직접 시도해보십시오.
ll /proc/<PID>/exe
pwdx <PID>
lsof -p <PID> | grep cwd
조금 늦었지만 모든 답변은 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;
}
편집 : Mark Lakata가보고 한 버그를 수정했습니다.
나는 사용한다:
ps -ef | grep 786
786을 PID 또는 프로세스 이름으로 교체하십시오.
pwdx <process id>
이 명령은 프로세스 경로를 실행중인 위치에서 가져옵니다.
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
"어디서나 작업 할 수있는"방법이 없습니다.
1 단계는 ArgV [0]를 확인하는 것입니다. 프로그램이 전체 경로로 시작되면 (보통) 전체 경로가 있습니다. 상대 경로에 따라 시작된 경우 동일한 보류가 발생합니다 (그러나 GetCWD ()를 사용하여 현재 작업 디렉토리를 가져와야합니다.
2 단계, 위의 보유가 없다면 프로그램의 이름을 얻은 다음 Argv [0]에서 프로그램 이름을 얻은 다음 환경에서 사용자의 경로를 얻고 적합한 것이 있는지 확인하십시오. 동일한 이름의 실행 가능한 바이너리.
ArgV [0]은 프로그램을 실행하는 프로세스에 의해 설정되므로 100% 신뢰할 수 없습니다.
감사해요 : 키와
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
}
또한 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);*/
아래 명령의 이름을 검색하는 과정에서 실행하는 프로세스 목록을 리디렉션 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
희망이 누군가가 도움이 됩니다.....
프로세스 이름으로가는 길을 찾으십시오
#!/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