Get the parent process id for a given pid

I was really surprised that there seems to be no posix or Cocoa API to get the parent process id on OS X when you already know a process id. This is expecially useful if you have started a process in form of an NSTask, but that task forks and so you cannot identify the process by -[NSTask processIdentifier] any more. This is now possible with the following small function by comparing the parent process id:

#include <sys/sysctl.h>

#define OPProcessValueUnknown UINT_MAX

int OPParentIDForProcessID(int pid)
/*" Returns the parent process id 
     for the given process id (pid). "*/
    struct kinfo_proc info;
    size_t length = sizeof(struct kinfo_proc);
    int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
    if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
        return OPProcessValueUnknown;
    if (length == 0)
        return OPProcessValueUnknown;
    return info.kp_eproc.e_ppid;

Have fun!


Print this page  PDF version


On Jun 24, 2007, Keffer wrote:


Just a little message to congrats you for the incredible application Picnic, now if it's can work over internet, it will be magic :)


On Mar 29, 2009, Noses wrote:

Nonsense. It's maybe not POSIX (who cares about that *today* - it's an ancient standard at most) but FreeBSD has had getppid(2) in unistd for ages and so has Darwin. Doing an "apropos pid" would have told you.

On Mar 30, 2009, Dirk wrote:


Hello, "Noses"!

You misread the purpose of this function. It delivers the parent pid if a given pid, *not* the current pid (which indeed getppid() delivers since POSIX 1).



On Apr 4, 2009, Ears wrote:

Listen, something smells silly

Dirk, if you put aside Noses' rudeness for a moment, you might see that he/she has a point. getppid() is not getpid(); it has an extra p which is for "parent".

On May 30, 2009, Mike wrote:

Read POSIX before making claims


See which states:

“The getppid() function shall return the parent process ID of the calling process.”

This means that getppid() will NOT work for any arbitrary process ID, just the currently-running process. Man pages on at least GNU/Linux and NetBSD agree with POSIX on this. I would imagine that OS X does, as well.

On Nov 5, 2009, KK wrote:


Noses running away without reading the intent of the function; and Ears not using "eyes and brains, but only ears" while reading this.

Leave a comment...

Your Name

Your Web site URL (optional)

Your e-mail address (optional)


Your comment here please:
Note: You can use Wiki markup to format your comment. No HTML please.