Skip to content

Instantly share code, notes, and snippets.

@eddyxu
Created September 21, 2010 02:50
Show Gist options
  • Save eddyxu/589115 to your computer and use it in GitHub Desktop.
Save eddyxu/589115 to your computer and use it in GitHub Desktop.
Get parent process id for specific process
pid_t getppid_for_process(pid_t pid) {
#if defined(__APPLE__)
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 -1;
if (length == 0)
return -1;
return info.kp_eproc.e_ppid;
#elif defined(__linux__)
char proc_filepath[BUFSIZE];
char buffer[BUFSIZE];
pid_t parent = -1;
memset(proc_filepath, 0, BUFSIZE);
snprintf(proc_filepath, BUFSIZE, "/proc/%d/status", pid);
FILE * fp = fopen(proc_filepath, "r");
while (fgets(buffer, BUFSIZE, fp) != NULL) {
if(strncmp(buffer, "PPid:", 5) == 0) {
sscanf(buffer, "PPid: %d", &parent);
break;
}
}
fclose(fp);
return parent;
#endif /* __linux__ */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment