温馨提示×

c++如何获取进程名

c++
小亿
82
2024-09-03 20:31:36
栏目: 编程语言

在 C++ 中,可以使用 Windows API 函数 GetModuleFileName 来获取当前进程的模块文件名(包括路径和文件名)

#include<iostream>
#include<windows.h>
#include<string>

std::string GetProcessName() {
    char buffer[MAX_PATH];
    GetModuleFileName(NULL, buffer, MAX_PATH);
    std::string processPath = buffer;
    size_t lastSlash = processPath.find_last_of("\\/");
    if (lastSlash != std::string::npos) {
        return processPath.substr(lastSlash + 1);
    } else {
        return processPath;
    }
}

int main() {
    std::string processName = GetProcessName();
    std::cout << "Current process name: "<< processName<< std::endl;
    return 0;
}

这个示例代码定义了一个名为 GetProcessName 的函数,该函数使用 GetModuleFileName 函数获取当前进程的模块文件名。然后,它从路径中提取文件名并返回。在 main 函数中,我们调用 GetProcessName 函数并输出结果。

请注意,这个示例仅适用于 Windows 平台。如果你需要在其他平台上实现类似的功能,你可能需要使用不同的方法。例如,在 Linux 上,你可以使用 /proc/self/exe 符号链接来获取当前进程的可执行文件路径。

0