cmacoslaunchdxpc

Getting the "real" parent process in case process spawned indirectly using launchd


I'm maintaining an OSX tool that reveal the parents tree of a selected process from the direct parent to its earliest ancestor (usually launchd).

However, this process chain may break if the examined process has indirectly spawned from launchd using events such as double clicking the bundle icon, or running the process from bash using command open. In these cases I'd like to see either bash or finder correspondingly.

Perhaps XPC messaging layer is the answer since I assume these events are passing to launchd through this mechanism. However, other available OSX frameworks are always welcome.

EDIT:

I understand that if a process detaches itself while running I couldn't restore it's ppid, but my goal is to trace the caller that initiate process creation.

thanks


Solution

  • This feature is undocumented. It might break at any OS update.

    typedef pid_t (*pidResolver)(pid_t pid);
    
    pidResolver resolver = dlsym(RTLD_NEXT, "responsibility_get_pid_responsible_for_pid");
    
    pid_t trueParentPid = resolver(pid);
    

    a) this method is private

    b) it needs root privileges

    For example: if you launch Safari.app a new process named "Safari Networking" is also created. If you inspect this in Activity Monitor you'll only see a ppid of 1.

    The above code snippet will return the pid of the Safari process. As seen when looking at "All Processes, Hierarchically" where "Safari Networking" is grouped under "Safari".