How do I get the path of a process in Unix / Linux

后端 未结 11 613
无人共我
无人共我 2020-12-02 04:31

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

Or is there some other way to do th

11条回答
  •  隐瞒了意图╮
    2020-12-02 04:56

    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.

    Here's a short example in Python:

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

    Here's the example in ANSI C as well:

    #include 
    #include 
    #include 
    #include 
    
    
    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 
    

提交回复
热议问题