/* * Print out the process command name for this process's ancestors, * up to init. * * Dan Cross */ #include #include #include #include #include #include #include #include #include #include kvm_t *kd; struct kinfo_proc * getparent(pid_t pid) { int c; struct kinfo_proc *r; c = 0; r = kvm_getprocs(kd, KERN_PROC_PID, (int)pid, sizeof(*r), &c); if (c != 1) return(NULL); return r; } void uptoinit(pid_t startpid, int printpid) { pid_t pid, ppid; struct kinfo_proc *proc; ppid = startpid; do { pid = ppid; proc = getparent(pid); if (proc == NULL) { perror("getparent"); kvm_close(kd); exit(EXIT_FAILURE); } if (printpid) printf("%d ", (int)pid); printf("%s\n", proc->p_comm); ppid = proc->p_ppid; } while (ppid != pid && ppid != 0); } int main(int argc, char *argv[]) { pid_t pid; int printpid, ch; printpid = 0; pid = getpid(); while ((ch = getopt(argc, argv, "ph?")) != -1) switch (ch) { case 'p': printpid = 1; break; case 'h': case '?': default: fprintf(stderr, "Usage: %s [ -p ] [ pid[s] ]\n", argv[0]); return(EXIT_FAILURE); break; /* NOTREACHED */ } argc -= optind; argv += optind; kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open"); if (kd == NULL) return(EXIT_FAILURE); if (argc == 0) uptoinit(getpid(), printpid); else while (*argv != NULL) { pid = atoi(*argv++); uptoinit(pid, printpid); } kvm_close(kd); return(EXIT_SUCCESS); }