Skip to content

Instantly share code, notes, and snippets.

@nevyn
Created May 29, 2014 17:20
Show Gist options
  • Save nevyn/2089d78e85b4ecfd5ba6 to your computer and use it in GitHub Desktop.
Save nevyn/2089d78e85b4ecfd5ba6 to your computer and use it in GitHub Desktop.
Prints the name of all the parent processes of this process.
#import <Foundation/Foundation.h>
#import <sys/sysctl.h>
#import <sys/proc_info.h>
#import <libproc.h>
// http://www.objectpark.net/en/parentpid.html
pid_t OPParentIDForProcessID(pid_t 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 0;
if (length == 0)
return 0;
return info.kp_eproc.e_ppid;
}
// http://stackoverflow.com/questions/3018054/retrieve-names-of-running-processes
NSString *nameForPid(pid_t pid)
{
char name[PROC_PIDPATHINFO_MAXSIZE] = "unknown";
proc_pidpath(pid, name, sizeof(name));
return [[NSString stringWithUTF8String:name] lastPathComponent];
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
pid_t pid = getpid();
int indentDepth = 0;
while(pid != 0) {
NSMutableString *indent = [NSMutableString new];
for(int i = 1; i < indentDepth; i++)
[indent appendString:@" "];
if(indentDepth != 0)
[indent appendString:@"└─ "];
printf("%sProcess[%d]: %s\n", [indent UTF8String], pid, [nameForPid(pid) UTF8String]);
pid = OPParentIDForProcessID(pid);
indentDepth++;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment