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!
Dirk
6 Comments
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.
Mistaken
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).
Greeting,
Dirk
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".
Read POSIX before making claims
@Ears:
See http://www.opengroup.org/onlinepubs/009695399/functions/getppid.html 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.
haha
Noses running away without reading the intent of the function; and Ears not using "eyes and brains, but only ears" while reading this.
Incredible.
Just a little message to congrats you for the incredible application Picnic, now if it's can work over internet, it will be magic :)
Cheers.