从进程名称获取进程ID

发布于 2024-10-08 22:16:44 字数 257 浏览 1 评论 0原文

你好 我正在尝试用 C 语言使用 Windows API 做一个项目。我的项目中的一小部分是获取 lsass.exe 的进程 ID。

我已经尝试过下面的程序,但它不起作用。 我读过有关 CreateToolhelp32Snapshot、Process32First、Process32Next 函数的内容,任何人都可以帮助我解释如何在代码中使用它们。

所以请帮助我。 我是 Windows API 的初学者,所以如果有人能给我推荐一本好的电子书供我参考,我将不胜感激。

Hi
i am trying to do a project using windows API in C language. The small part in my project is to get process ID of lsass.exe.

i have tried the program below but it wont work.
i have read about the CreateToolhelp32Snapshot, Process32First, Process32Next functions can anyone help me explaining how to use them in the code.

So please help me.
i am a beginner to windows API so i will appreciate it if anyone can suggest me an good ebook to refer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

千寻… 2024-10-15 22:16:44

由于进程名称可能有多个实例在运行,因此进程的映像名称和 PID 之间不存在一对一的关联。您必须按照 Burgos 的描述,使用 EnumProcesses 枚举进程并检查每个进程的基本模块名称。

FWIW,.Net 通过提供 GetProcessesByName API 来解决此问题,该 API 返回进程对象的集合。当然对你没有多大用处:-(

Because there might be several instances of a process name running, there is no one-to-one correlation between a process's image name and a PID. You'll have to enumerate the processes and check the base module names for each one as Burgos describes, by using EnumProcesses.

FWIW, .Net approaches this problem by providing the GetProcessesByName API, which returns a collection of process objects. Not much use to you of course :-(

请你别敷衍 2024-10-15 22:16:44

我不知道更简单的方法。这是通过查找每个正在运行的 PID 并将其名称与“lsass.exe”进行比较来实现的。

    // pid.cpp : Defines the entry point for the console application.

    #include "stdafx.h"
    #include <windows.h>
    #include <psapi.h>

    int PrintProcessNameAndID( DWORD processID, const char *name )
    {
        TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

        // Get a handle to the process.

        HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                               PROCESS_VM_READ,
                               FALSE, processID );

        // Get the process name.

        if (NULL != hProcess )
        {
            HMODULE hMod;
            DWORD cbNeeded;

            if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
                 &cbNeeded) )
            {
                GetModuleBaseName( hProcess, hMod, szProcessName, 
                                   sizeof(szProcessName)/sizeof(TCHAR) );
            }
        }


        if(strcmp(szProcessName, name) == 0) // right process
        {
                    CloseHandle(hProcess);
            return 1;
        }

        // Release the handle to the process.

        CloseHandle( hProcess );
        return 0;
     }

    int find(const char *name)
    {
    // Get the list of process identifiers.

        DWORD aProcesses[1024], cbNeeded, cProcesses;
        unsigned int i;

        if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        {
            return 1;
        }


        // Calculate how many process identifiers were returned.

        cProcesses = cbNeeded / sizeof(DWORD);

        // Print the name and process identifier for each process.

        for ( i = 0; i < cProcesses; i++ )
        {
            if( aProcesses[i] != 0 )
            {
                if(PrintProcessNameAndID( aProcesses[i], name ))
                {
                    //found it
                    _tprintf("%d %s\n", aProcesses[i], name);
                }
               }
        }
 }

    int _tmain(int argc, _TCHAR* argv[])
    {
        find("lsass.exe");
        return 0;
    }

I don't know for simplier way. This is working by finding every running PID and comparing its name to "lsass.exe".

    // pid.cpp : Defines the entry point for the console application.

    #include "stdafx.h"
    #include <windows.h>
    #include <psapi.h>

    int PrintProcessNameAndID( DWORD processID, const char *name )
    {
        TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

        // Get a handle to the process.

        HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                               PROCESS_VM_READ,
                               FALSE, processID );

        // Get the process name.

        if (NULL != hProcess )
        {
            HMODULE hMod;
            DWORD cbNeeded;

            if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
                 &cbNeeded) )
            {
                GetModuleBaseName( hProcess, hMod, szProcessName, 
                                   sizeof(szProcessName)/sizeof(TCHAR) );
            }
        }


        if(strcmp(szProcessName, name) == 0) // right process
        {
                    CloseHandle(hProcess);
            return 1;
        }

        // Release the handle to the process.

        CloseHandle( hProcess );
        return 0;
     }

    int find(const char *name)
    {
    // Get the list of process identifiers.

        DWORD aProcesses[1024], cbNeeded, cProcesses;
        unsigned int i;

        if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        {
            return 1;
        }


        // Calculate how many process identifiers were returned.

        cProcesses = cbNeeded / sizeof(DWORD);

        // Print the name and process identifier for each process.

        for ( i = 0; i < cProcesses; i++ )
        {
            if( aProcesses[i] != 0 )
            {
                if(PrintProcessNameAndID( aProcesses[i], name ))
                {
                    //found it
                    _tprintf("%d %s\n", aProcesses[i], name);
                }
               }
        }
 }

    int _tmain(int argc, _TCHAR* argv[])
    {
        find("lsass.exe");
        return 0;
    }
提笔书几行 2024-10-15 22:16:44

这是对 Luis G. Costantini R. 代码的修改。

它使用MFC:

#include "TlHelp32.h"

BOOL GetProcessList(const TCHAR *processname, CArray<DWORD> &PIDs)
{
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    // Take a snapshot of all processes in the system.
    HANDLE 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 == _tcsicmp(processname, pe32.szExeFile))
        {
            PIDs.Add(pe32.th32ProcessID);
        }
    }
    while (::Process32Next(hProcessSnap, &pe32));

    ::CloseHandle(hProcessSnap);
    return TRUE;
}

This is modification of Luis G. Costantini R. code.

It uses MFC:

#include "TlHelp32.h"

BOOL GetProcessList(const TCHAR *processname, CArray<DWORD> &PIDs)
{
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    // Take a snapshot of all processes in the system.
    HANDLE 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 == _tcsicmp(processname, pe32.szExeFile))
        {
            PIDs.Add(pe32.th32ProcessID);
        }
    }
    while (::Process32Next(hProcessSnap, &pe32));

    ::CloseHandle(hProcessSnap);
    return TRUE;
}
叶落知秋 2024-10-15 22:16:44

有一个如何使用 CreateToolhelp32SnapshotProcess32FirstProcess32Next 的示例(您必须添加错误句柄等,并包含 tlhelp32 .h 在您的代码中)。顺便说一句,此函数与 Windows NT 不兼容:

BOOL GetProcessList(const char *processname, DWORD **processIds, int *numprocess)
{
    HANDLE hProcessSnap;
    PROCESSENTRY32 pe32;
    DWORD *processIdsTmp;

    *processIds = NULL;
    *numprocess = 0;
    // 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 == strcasecmp(processname, pe32.szExeFile))
        {
            processIdsTmp = realloc(*processIds, sizeof(DWORD) * ((*numprocess) + 1));
            if (NULL == processIdsTmp)
            {
                free(*processIds);
                *processIds = NULL;
                *numprocess = 0;
                CloseHandle( hProcessSnap );          // clean the snapshot object
                return( FALSE );
            }
            *processIds = processIdsTmp;
            (*processIds)[(*numprocess)++] = pe32.th32ProcessID;
        }
    } while( Process32Next( hProcessSnap, &pe32 ) );

    CloseHandle( hProcessSnap );
    return( TRUE );     
}

这里是使用此函数的完整示例。

There is an example of how to use CreateToolhelp32Snapshot, Process32First, Process32Next (You have to add error handles, etc. and include tlhelp32.h in your code). By the way this functions are not compatible with Windows NT:

BOOL GetProcessList(const char *processname, DWORD **processIds, int *numprocess)
{
    HANDLE hProcessSnap;
    PROCESSENTRY32 pe32;
    DWORD *processIdsTmp;

    *processIds = NULL;
    *numprocess = 0;
    // 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 == strcasecmp(processname, pe32.szExeFile))
        {
            processIdsTmp = realloc(*processIds, sizeof(DWORD) * ((*numprocess) + 1));
            if (NULL == processIdsTmp)
            {
                free(*processIds);
                *processIds = NULL;
                *numprocess = 0;
                CloseHandle( hProcessSnap );          // clean the snapshot object
                return( FALSE );
            }
            *processIds = processIdsTmp;
            (*processIds)[(*numprocess)++] = pe32.th32ProcessID;
        }
    } while( Process32Next( hProcessSnap, &pe32 ) );

    CloseHandle( hProcessSnap );
    return( TRUE );     
}

here is a complete example of the use of this funcions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文