Programmatically retrieving the absolute path of an OS X command-line app

后端 未结 7 501
予麋鹿
予麋鹿 2020-11-27 15:04

On Linux, an application can easily get its absolute path by querying /proc/self/exe. On FreeBSD, it\'s more involved, since you have to build up a sysctl call

7条回答
  •  天涯浪人
    2020-11-27 15:09

    I believe there is much more elegant solution, which actually works for any PID, and also returns the absolute path directly:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main (int argc, char* argv[])
    {
        int ret;
        pid_t pid; 
        char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
    
        pid = getpid();
        ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf));
        if ( ret <= 0 ) {
            fprintf(stderr, "PID %d: proc_pidpath ();\n", pid);
            fprintf(stderr, "    %s\n", strerror(errno));
        } else {
            printf("proc %d: %s\n", pid, pathbuf);
        }
    
        return 0;
    }
    

提交回复
热议问题