gpt4 book ai didi

c - 按名称获取 C 中的进程 ID

转载 作者:可可西里 更新时间:2023-11-01 13:08:32 26 4
gpt4 key购买 nike

我正在尝试通过进程名称(例如,notepad.exe)获取进程 ID,但 Stack Overflow 上的先前解决方案似乎无法正常工作。这是我尝试过的:

DWORD FindProcessId(const char *processname)
{
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
DWORD result = NULL;

// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hProcessSnap) return(FALSE);

// Retrieve information about the first process,
// and exit if unsuccessful
if (!Process32First(hProcessSnap, &pe32))
{
CloseHandle(hProcessSnap); // Clean the snapshot object
return(FALSE);
}

do
{
if (0 == _stricmp(processname, pe32.szExeFile))
{
result = pe32.th32ProcessID;
break;
}
} while (Process32Next(hProcessSnap, &pe32));

CloseHandle(hProcessSnap);

return result;
}

我传入“notepad.exe”并确认它正在我的系统上运行,并且该应用程序正在以具有所需正确权限的管理员身份运行。海拔是这样完成的:

        if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath)))
{
// Launch itself as administrator.
sei.lpVerb = TEXT("runas");
sei.lpFile = szPath;
sei.hwnd = NULL;
sei.nShow = SW_NORMAL;

if (!ShellExecuteEx(&sei))
{
MessageBox(NULL, TEXT("The program needs to be elevated to work properly."), APP_TITLE, MB_OK);
return -1;
}
}
return 0;

它永远找不到进程 ID - 每次都返回 Null。

这是使用 C,而不是 C++。

最佳答案

解决方案是在获取进程快照后简单地设置pe32.dwSize。在此处完成固定代码:

DWORD FindProcessId(const char *processname)
{
HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
DWORD result = 0;

// Take a snapshot of all processes in the system.
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hProcessSnap) return(FALSE);

pe32.dwSize = sizeof(PROCESSENTRY32); // <----- IMPORTANT

// Retrieve information about the first process,
// and exit if unsuccessful
if (!Process32First(hProcessSnap, &pe32))
{
CloseHandle(hProcessSnap); // clean the snapshot object
printf("!!! Failed to gather information on system processes! \n");
return(0);
}

do
{
printf("Checking process %ls\n", pe32.szExeFile);
if (0 == strcmp(processname, pe32.szExeFile))
{
result = pe32.th32ProcessID;
break;
}
} while (Process32Next(hProcessSnap, &pe32));

CloseHandle(hProcessSnap);

return result;
}

关于c - 按名称获取 C 中的进程 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874381/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com