[linux] 유닉스 / 리눅스에서 프로세스의 경로를 얻는 방법

Windows 환경에는 프로세스를 실행중인 경로를 얻는 API가 있습니다. 유닉스 / 리눅스에 비슷한 것이 있습니까?

아니면 이러한 환경에서 다른 방법이 있습니까?



답변

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에만 해당됩니다.

유닉스도 필요하다면 다음이 필요합니다.

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]에서 프로그램 이름을 얻은 다음 환경에서 사용자의 PATH를 가져 와서 해당 경로가 적합한 지 확인하는 것입니다. 같은 이름의 실행 바이너리.

argv [0]은 프로그램을 실행하는 프로세스에 의해 설정되므로 100 % 신뢰할 수 없습니다.