Skip to content

Instantly share code, notes, and snippets.

@sevagh sevagh/pppid.h
Created Nov 30, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.