通过线程ID查找进程

通过线程ID查找进程

我的一个程序为了调试目的输出了它的线程 ID。出于测试原因,我想终止该线程 ID 所属的进程。

如果我有线程 ID,那么如何获取进程 ID 以便能够使用它taskkill

我试过

  • tasklist但它似乎没有用于切换主题 ID 的开关。
  • 系统内部进程探索器的“查找句柄”功能,它可以工作,但我需要一些可以在批处理文件中自动执行的功能
  • 系统内部处理 -a Thread,但这似乎不起作用。handle -a | find "Thread"效果更好,但我丢失了流程信息

答案1

您可以使用批处理文件这样做:

批处理文件killprocess.bat:

@echo off
set processhandle=
set description=
set handle=%1
IF "%handle%." == "." (
  echo Usage: killprocess threadID
  exit/b
)

FOR /F "tokens=*" %%A IN ('WMIC PATH Win32_thread WHERE handle^=%handle% GET Processhandle /VALUE ^| find "="') DO set "%%A"
FOR /F "tokens=*" %%A IN ('WMIC PATH Win32_process WHERE handle^=%processhandle% GET Description /VALUE ^| find "="') DO set "%%A"

IF "%ProcessHandle%." == "." (
  echo ThreadID not found
  exit/b
)

echo I'm going to kill %Description% (Processhandle = %processhandle%) if you don't press Q in 5 seconds
echo (or you can press Y to continue)
choice /N /T 5 /C yq /D y
if "%errorlevel%"=="2" goto :eof

echo Killing %Description% (Processhandle = %processhandle%)
Taskkill /PID %processhandle% /T /F

用法如下:
killprocess 13008

编辑:我还添加了中止选项(选择)和被终止进程的描述。如果您不想要它,可以将其删除。

答案2

这是我的 C++ 解决方案,如果有人想使用它,我将其许可为 CC0/公共领域。我很少用 C++ 实现,所以请原谅错误。

#include "stdafx.h"
#include <sstream>
#include <windows.h>
#include <stdio.h>
#include <iostream>
int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        std::cout << "Usage: " << argv[0] << " <Thread ID>" << std::endl;
        std::cout << "Returns the process ID of a thread." << std::endl;
        std::cout << "Errorlevels:" << std::endl;
        std::cout << "   0 success" << std::endl;
        std::cout << "   1 too few arguments" << std::endl;
        std::cout << "   2 error parsing thread ID" << std::endl;
        std::cout << "   3 error opening thread" << std::endl;
        return 1;
    }

    std::istringstream iss(argv[1]);
    int threadId;

    if (iss >> threadId)
    {
        std::cout << threadId << std::endl;
        HANDLE threadHandle = OpenThread(THREAD_QUERY_INFORMATION, false, (DWORD)threadId);
        if (threadHandle)
        {
            DWORD pid = GetProcessIdOfThread(threadHandle);
            CloseHandle(threadHandle);
            std::cout << pid << std::endl;
            return 0;
        }
        std::cerr << "Error opening thread. Perhaps run as admin or thread does not exist?";
        return 3;
    }
    std::cerr << "Error parsing thread ID. Use decimal, not hex?";
    return 2;
}

相关内容