如何在C++中获取当前进程 ID 和计算机名称

how to get current process ID and machine name in C++

本文关键字:ID 进程 计算机名 C++ 获取      更新时间:2023-10-16

在 C# 中,获取当前进程 ID 和计算机名称非常简单:

int processID = Process.GetCurrentProcess().Id;
string machineName = Environment.MachineName;

如何在本机C++中检索它们?

正如你所评论的,该平台是Windows 7,WINAPI提供了GetCurrentProcessId()和GetComputerName()。

GetComputerName()的简单示例:

const int BUF_SIZE = MAX_COMPUTERNAME_LENGTH + 1;
char buf[BUF_SIZE] = "";
DWORD size = BUF_SIZE;
if (GetComputerNameA(buf, &size)) // Explicitly calling ANSI version.
{
    std::string computer_name(buf, size);
}
else
{
    // Handle failure.
}

getpid() &&gethostname() - 使用man来了解它们...

#ifdef _WIN32
 return GetCurrentProcessId(); 
#else
 return ::getpid();
#endif