expose the GetPidByName API of dumpstate
Bug: 32248316
This API is used by external dumpstate module
1) add unittest for GetPidByName
2) change the API name to c++ style
3) Test: dumpstate_test pass
Change-Id: I5eb80e0d1f1ef0f09b77ac3affd8a9b41d64f679
Signed-off-by: Ecco Park <eccopark@google.com>
diff --git a/cmds/dumpstate/DumpstateUtil.cpp b/cmds/dumpstate/DumpstateUtil.cpp
index 9faa63e..d517797 100644
--- a/cmds/dumpstate/DumpstateUtil.cpp
+++ b/cmds/dumpstate/DumpstateUtil.cpp
@@ -18,6 +18,7 @@
#include "DumpstateUtil.h"
+#include <dirent.h>
#include <fcntl.h>
#include <sys/prctl.h>
#include <sys/wait.h>
@@ -25,7 +26,10 @@
#include <vector>
+#include <android-base/file.h>
#include <android-base/properties.h>
+#include <android-base/stringprintf.h>
+#include <android-base/strings.h>
#include <cutils/log.h>
#include "DumpstateInternal.h"
@@ -342,3 +346,31 @@
return status;
}
+
+int GetPidByName(const std::string& ps_name) {
+ DIR* proc_dir;
+ struct dirent* ps;
+ unsigned int pid;
+ std::string cmdline;
+
+ if (!(proc_dir = opendir("/proc"))) {
+ MYLOGE("Can't open /proc\n");
+ return -1;
+ }
+
+ while ((ps = readdir(proc_dir))) {
+ if (!(pid = atoi(ps->d_name))) {
+ continue;
+ }
+ android::base::ReadFileToString("/proc/" + std::string(ps->d_name) + "/cmdline", &cmdline);
+ if (cmdline.find(ps_name) == std::string::npos) {
+ continue;
+ } else {
+ closedir(proc_dir);
+ return pid;
+ }
+ }
+ MYLOGE("can't find the pid\n");
+ closedir(proc_dir);
+ return -1;
+}