【问题标题】:Can I suspend a process except one thread?我可以挂起一个线程以外的进程吗?
【发布时间】:2013-05-17 01:27:37
【问题描述】:

我要挂起(或暂停)除一个线程之外的进程。

我尝试使用 SuspendThread(Api Function),结果是进程线程变成了不负责任的状态。

这不是我想要的。我想恢复一个我必须做的主要工作的线程。

我该如何解决这个问题?请给出你的想法。

谢谢。

【问题讨论】:

    标签: c++ dll mfc system


    【解决方案1】:

    您可以调用CreateToolhelp32Snapshot 来获取属于某个进程的线程列表。获得该列表后,只需对其进行迭代并挂起与当前线程 ID 不匹配的每个线程。下面的示例未经测试,但应该可以正常工作。

    #include <windows.h>
    #include <tlhelp32.h>
    
    // Pass 0 as the targetProcessId to suspend threads in the current process
    void DoSuspendThread(DWORD targetProcessId, DWORD targetThreadId)
    {
        HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
        if (h != INVALID_HANDLE_VALUE)
        {
            THREADENTRY32 te;
            te.dwSize = sizeof(te);
            if (Thread32First(h, &te))
            {
                do
                {
                    if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) 
                    {
                        // Suspend all threads EXCEPT the one we want to keep running
                        if(te.th32ThreadID != targetThreadId && te.th32OwnerProcessID == targetProcessId)
                        {
                            HANDLE thread = ::OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
                            if(thread != NULL)
                            {
                                SuspendThread(thread);
                                CloseHandle(thread);
                            }
                        }
                    }
                    te.dwSize = sizeof(te);
                } while (Thread32Next(h, &te));
            }
            CloseHandle(h);    
        }
    }
    

    【讨论】:

    • 不幸的是,我无法包含“windows.h”。因为我没有使用MFC。我必须通过 c 代码实现 CreateToolhelp32SnapShot 功能。我该怎么做?
    • CreateToolhelp32SnapShot 贴在tlhelp32.h 中。只需删除 windows.h 的包含,就可以了。如果这不能解决编译问题,您可能需要在 stdafx.h 文件中添加“tlhelp32.h”。
    • 感谢您的帮助。当我编写代码并运行时,我的计算机被挂起。我只需要暂停一个进程。请告诉我路。
    • 我将获取我的进程线程列表,然后挂起除特殊线程 ID 之外的所有线程。
    • 如果您尝试挂起远程进程中的线程,您需要在调用 CreateToolhelp32SnapShot 时指定进程 ID。还要确保不要挂起当前线程。如果你这样做,它将永远不会完成循环和挂起线程。我建议您阅读 CreateToolhelp32SnapShot 的文档。
    【解决方案2】:

    据我所知,您不能暂停除一个线程之外的进程...因为当进程退出时,所有线程也将退出。如果你想代替线程,你可以生成一个子进程并使用它..

    【讨论】:

    • 您可以,但 Windows 不提供单个 API 调用来执行此操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    相关资源
    最近更新 更多