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

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); 
}


本文为@艺文笔记原创文章,转载请注明出处:https://www.xuwenyan.com/archives/233,非常感谢!
上一篇:  下一篇: