# CreateToolhelp32Snapshot

CreateToolhelp32Snapshot은 시스템의 프로세스, 스레드, 모듈 등의 스냅샷을 생성하여 프로세스 열거에 필수적으로 사용됩니다.

굳이 스냅샷을 생성하여 프로세스를 가져오는 이유로는, 실시간으로 프로세스를 열거하다가 해당 프로세스가 종료하게 된다면 예외 상황이 발생할 수 있기 때문입니다.

```cpp
HANDLE CreateToolhelp32Snapshot(
  [in] DWORD dwFlags,
  [in] DWORD th32ProcessID
);
```

| 인자            | 설명      | 보편적인 값               |
| ------------- | ------- | -------------------- |
| dwFlags       | 스냅샷 플래그 | `TH32CS_SNAPPROCESS` |
| th32ProcessID | 프로세스 ID | 0(모든 프로세스)           |

## Example

```cpp
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
using namespace std;

DWORD getProcId(const wchar_t* processName) {
    // 메모리에 로드된 프로세스 스냅샷 생성
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) {
        wcout << L"Failed to take a snapshot" << endl;
        return 0;
    }

    // 스냅샷을 순회하며 저장할 프로세스 변수 생성
    PROCESSENTRY32W pe;
    pe.dwSize = sizeof(PROCESSENTRY32W);

    if (Process32FirstW(hSnapshot, &pe)) {
        do {
            // 대소문자 구분 없이 비교하여 일치할 경우 조건분기
            if (_wcsicmp(pe.szExeFile, processName) == 0) {
                wcout << L"Succeed to find a process : " << pe.szExeFile << endl;
                CloseHandle(hSnapshot);
                return pe.th32ProcessID;
            }
        } while (Process32NextW(hSnapshot, &pe));
    }

    CloseHandle(hSnapshot);
    wcout << L"Failed to find a process in memory" << endl;
    return 0;
}

int main() {
    DWORD pid = getProcId(L"notepad.exe");
    return 0;
}
```

## References

{% embed url="<https://learn.microsoft.com/ko-kr/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentestwiki.com/defense-evasion/windows-api/createtoolhelp32snapshot.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
