Get real path of application from pid?

人盡茶涼 提交于 2019-11-28 17:17:24

It's quite easy to get the process name / location if you know the PID, just use proc_name or proc_pidpath. Have a look at the following example, which provides the process path:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <libproc.h>

int main (int argc, char* argv[])
{
    pid_t pid; int ret;
    char pathbuf[PROC_PIDPATHINFO_MAXSIZE];

    if ( argc > 1 ) {
        pid = (pid_t) atoi(argv[1]);
        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;
}

You can use the Activity Monitor - http://en.wikipedia.org/wiki/Activity_Monitor

Or in the Terminal App you can use:

ps xuwww -p PID

PIDis the process id you are looking for More help on 'ps`command you can find with

man ps

Try use lsof

example:

lsof -p 1066 -Fn | awk 'NR==2{print}' | sed "s/n\//\//"

output:
/Users/user/Library/Application Support/Sublime Text 2/Packages

If the PID is the PID of a "user application", then you can get the NSRunningApplication of the app like that:

NSRunningApplication * app = [NSRunningApplication  
    runningApplicationWithProcessIdentifier:pid
];

And to print the path of the executable:

NSLog(@"Executable of app: %@", app.executableURL.path);

the app bundle itself is here

NSLog(@"Executable of app: %@", app.bundleURL.path);

However this won't work with system or background processes, it's limited to user apps (those typically visible in the dock after launch). The NSRunningApplication object allows to to check if the app is ative, to hide/unhide it and do all other kind of neat stuff.

Just thought I mention it here for completeness. If you want to work with arbitrary processes, then the accepted answer is of course better.

I would like to make a better ssh-copy-id in bash only!! For that, i have to know where is sshd to ask him his actual config. On some system i have multiple sshd and which is not my friend. Also on some macOS the ps command didn't show the full path for sshd.

lsof -p $PPID | grep /sshd | awk '{print $9}'

this return

/usr/sbin/sshd

after i could ask for

sudo /usr/sbin/sshd -T | grep authorizedkeysfile

this return, on some system

authorizedkeysfile .ssh/authorized_keys

so i have to put in .ssh/authorized_keys

RLT

Use this code to find the processinfo psn.

Then use following function to get location,

OSStatus GetProcessBundleLocation (const ProcessSerialNumber *psn, FSRef *location);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!