Browse Source

增加取指定PID工作目录

xx 2 years ago
parent
commit
1e77fccc5f
3 changed files with 38 additions and 1 deletions
  1. 1 1
      CMakeLists.txt
  2. 7 0
      include/util/process.h
  3. 30 0
      src/util/process.cpp

+ 1 - 1
CMakeLists.txt

@@ -6,7 +6,7 @@ set(PROJECT_NAME ylib)
 project(${PROJECT_NAME})
 
 set(CMAKE_CXX_STANDARD 20)
-
+ 
 #set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/lib)
 # 设置自定义配置类型
 set(CMAKE_CONFIGURATION_TYPES "Debug;Release;RelWithDebInfo;MinSizeRel;ReleaseMT" CACHE STRING "Build config types" FORCE)

+ 7 - 0
include/util/process.h

@@ -33,6 +33,13 @@ namespace ylib
 		// 是否存在
 		size_t exist(const std::string& filepath);
 		bool exist(size_t pid);
+		/// <summary>
+		/// 取工作目录
+		/// </summary>
+		/// <param name="pid"></param>
+		/// <returns></returns>
+		std::string work_directory(size_t pid);
+
 #ifdef _WIN32
 		// 检测多开
 		bool already_running(const std::string& name);

+ 30 - 0
src/util/process.cpp

@@ -284,7 +284,37 @@ bool ylib::process::exist(size_t pid)
     }
 #endif
 }
+std::string ylib::process::work_directory(size_t pid)
+{
+#ifdef _WIN32
+    char buffer[MAX_PATH];
+    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
+    if (hProcess) {
+        if (GetModuleFileNameEx(hProcess, NULL, buffer, MAX_PATH)) {
+            CloseHandle(hProcess);
+            std::string::size_type pos = std::string(buffer).find_last_of("\\/");
+            return std::string(buffer).substr(0, pos);
+        }
+        CloseHandle(hProcess);
+    }
+#else
+    char buffer[PATH_MAX];
+    std::ostringstream path;
+    path << "/proc/" << pid << "/exe";
+    ssize_t len = readlink(path.str().c_str(), buffer, sizeof(buffer) - 1);
+    if (len != -1) {
+        buffer[len] = '\0';
+        std::string fullPath(buffer);
+        std::string::size_type pos = fullPath.find_last_of("/");
+        return fullPath.substr(0, pos);
+    }
+#endif
+    return "";
+}
+
+
 #ifdef _WIN32
+
 // 检测多开
 bool ylib::process::already_running(const std::string& name)
 {