Skip to content

Commit

Permalink
mx_proc: Add mx_proc_get_parent
Browse files Browse the repository at this point in the history
Add utility function to get the parent pid of a process from procfs.
  • Loading branch information
donald committed Aug 24, 2021
1 parent c593fb5 commit 63fa968
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
34 changes: 34 additions & 0 deletions mx_proc.c
Original file line number Diff line number Diff line change
Expand Up @@ -450,3 +450,37 @@ struct mx_proc_info *mx_proc_tree_proc_info(struct mx_proc_tree *tree, pid_t pid

return &(ptn->pinfo);
}

/*
* get parent pid of pid
* return -1 if pid is not found
*/
pid_t mx_proc_get_parent(pid_t pid) {
char statfilename[32]; // "/proc/2147483647/stat" = 22
FILE *statfile;
pid_t parent;
int n;
char linebuf[256]; // "2147483647 (max128chars) X 2147483647 " = 156

if (pid == 0) // no need to try /proc/0/stat
return -1;

snprintf(statfilename, sizeof(statfilename), "/proc/%d/stat", pid);
statfile = fopen(statfilename, "r");
if (statfile==NULL)
return -1;
/*
* we can't just scanf(statfile, "%*d %*s %*c %d", &parent) because the comm might contain whitespace
* e.g. "579 (UVM global queu) S 2 0 0 0 -1 2129984...."
* all later fields are integer, so position at the last ")"
*/
fgets(linebuf, sizeof(linebuf), statfile);
fclose(statfile);
char *c = strrchr(linebuf, ')');
if (c == NULL)
return -1;
n = sscanf(c, ") %*c %d", &parent);
if (n != 1)
return -1;
return parent;
}
2 changes: 1 addition & 1 deletion mx_proc.h
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,5 @@ int mx_proc_tree(struct mx_proc_tree **newtree);
int mx_proc_tree_free(struct mx_proc_tree **tree);

struct mx_proc_info *mx_proc_tree_proc_info(struct mx_proc_tree *tree, pid_t pid);

pid_t mx_proc_get_parent(pid_t pid);
#endif

0 comments on commit 63fa968

Please sign in to comment.