Skip to content

Instantly share code, notes, and snippets.

@sevagh
Created November 30, 2019 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sevagh/72ed87803f0cc4de2eaf7c888045370c to your computer and use it in GitHub Desktop.
Save sevagh/72ed87803f0cc4de2eaf7c888045370c to your computer and use it in GitHub Desktop.
Get pid at any depth with procfs
#include <sys/types.h>
#include <algorithm>
#include <cctype>
#include <fstream>
#include <string>
#define PROC_STR "/proc/%s/stat"
pid_t
_getpppid(const char *, int);
pid_t
getpppid(int level)
{
if (level < 0) {
return level;
}
if (level == 0) {
return _getpppid("self", 0);
}
if (level == 1) {
return _getpppid("self", 3);
}
return _getpppid(std::to_string(getpppid(level - 1)).c_str(), 3);
}
pid_t
_getpppid(const char *prefix, int skip_whitespaces)
{
char buf[64];
sprintf(buf, PROC_STR, prefix);
std::ifstream f(buf);
std::string buffer;
while (std::getline(f, buffer)) {
std::string pid;
pid_t pid_;
int space_ctr = 0;
bool parens_open = false;
for (int i = 0; i < buffer.length(); ++i) {
if (buffer.at(i) == '(') {
parens_open = true;
}
if (buffer.at(i) == ')') {
parens_open = false;
}
if (!parens_open) {
if (isspace(buffer.at(i))) {
if (space_ctr == skip_whitespaces) {
break;
}
pid.clear();
space_ctr++;
continue;
}
}
if (isdigit(buffer.at(i))) {
pid.push_back(buffer.at(i));
}
}
return std::stoi(pid);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment