当前位置:首页 > c++ > C++如何实现挂起进程、恢复进程

C++如何实现挂起进程、恢复进程

xuwenyan2年前 (2021-02-22)c++2110

1:枚举进程的所有线程,使用SuspendThread函数挂起每一个线程,需要恢复时使用ResumeThread函数恢复。因为挂起和恢复的顺序是不可预知的,所以可能会导致一些多线程程序崩溃,单线程程序可能不受影响。

void SuspendProcess(DWORD process_id) { 
  HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);    
  THREADENTRY32 threadEntry; 
  threadEntry.dwSize = sizeof(THREADENTRY32);       
  Thread32First(hThreadSnapshot, &threadEntry);
  do {
    if (threadEntry.th32OwnerProcessID == process_id) {
      HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,threadEntry.th32ThreadID);
      SuspendThread(hThread);
      CloseHandle(hThread); 
    }
  } while (Thread32Next(hThreadSnapshot, &threadEntry));   
  CloseHandle(hThreadSnapshot); 
}

void ResumeProcess(DWORD process_id) { 
  HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);    
  THREADENTRY32 threadEntry; 
  threadEntry.dwSize = sizeof(THREADENTRY32);       
  Thread32First(hThreadSnapshot, &threadEntry);
  do {
    if (threadEntry.th32OwnerProcessID == process_id) {
      HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,threadEntry.th32ThreadID);
      ResumeThread(hThread);
      CloseHandle(hThread); 
    }
  } while (Thread32Next(hThreadSnapshot, &threadEntry));   
  CloseHandle(hThreadSnapshot); 
}

2:使用NtSuspendProcess挂起进程,这个方法在xp系统就已经支持,使用NtResumeProcess函数恢复。

typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle); 
void SuspendProcess(DWORD process_id) {
  HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process_id));
  NtSuspendProcess pfnNtSuspendProcess = 
 (NtSuspendProcess)GetProcAddress(GetModuleHandle("ntdll"), "NtSuspendProcess");
  pfnNtSuspendProcess(processHandle); 
  CloseHandle(processHandle); 
}

typedef LONG (NTAPI *NtResumeProcess)(IN HANDLE ProcessHandle); 
void ResumeProcess(DWORD process_id) {
  HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, process_id));
  NtResumeProcess pfnNtResumeProcess = 
 (NtResumeProcess)GetProcAddress(GetModuleHandle("ntdll"), "NtResumeProcess");
  pfnNtResumeProcess(processHandle); 
  CloseHandle(processHandle); 
}

3:使用调试器的方式,调用DebugActiveProcess函数挂起,调用DebugActiveProcessStop函数恢复。

void SuspendProcess(DWORD process_id) {
  DebugActiveProcess(process_id); 
}

void ResumeProcess(DWORD process_id) {
  DebugActiveProcessStop(process_id); 
}

    文章作者:xuwenyan
    版权声明:本文为本站原创文章,转载请注明出处,非常感谢,如版权漏申明或您觉得任何有异议的地方欢迎与本站取得联系。

    发表评论

    访客

    ◎欢迎参与讨论,请在这里发表您的看法和观点。