进程暂停

有的时候跑实验,CPU占用率非常的高。有的时候想收发邮件,聊个qq都不行。任务管理器里面也没有暂停进程的功能,我就想能么能自己开发一个暂停进程的功能。查找了Windows api没有发现有暂停进程的api,只找到了一个暂停线程的api。

 

上网找了一下资料发现code project上有一个类似的工具,做法是通过api找到一个进程下的所有线程,然后把进程的所有线程暂停,唤醒的时候就是把所有的线程唤醒。这样做可能有一个问题,就是有的线程已经暂停了,我们在唤醒的时候把原本是暂停的线程也唤醒了,这样很有可能破坏程序的逻辑。当然对于单线程程序来说,就不存在这样的问题。

 

下面是实现这个的核心代码:

代码
BOOL CProcessManagerDlg::PauseResumeThreadList(DWORD dwOwnerPID, BOOL bResumeThread) 

    HANDLE        hThreadSnap 
=  NULL; 
    BOOL          bRet        
=  FALSE; 
    THREADENTRY32 te32        
=  { 0 }; 
 
    
//  Take a snapshot of all threads currently in the system. 

    hThreadSnap 
=  CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,  0 ); 
    
if  (hThreadSnap  ==  INVALID_HANDLE_VALUE) 
        
return  (FALSE); 
 
    
//  Fill in the size of the structure before using it. 

    te32.dwSize 
=   sizeof (THREADENTRY32); 
 
    
//  Walk the thread snapshot to find all threads of the process. 
    
//  If the thread belongs to the process, add its information 
    
//  to the display list.
 
    
if  (Thread32First(hThreadSnap,  & te32)) 
    { 
        
do  
        { 
            
if  (te32.th32OwnerProcessID  ==  dwOwnerPID) 
            {
                HANDLE hThread 
=  OpenThread(THREAD_SUSPEND_RESUME, FALSE, te32.th32ThreadID);
                
if  (bResumeThread)
                {
                    ResumeThread(hThread);
                }
                
else
                {
                    SuspendThread(hThread);
                }
                CloseHandle(hThread);
            } 
        }
        
while  (Thread32Next(hThreadSnap,  & te32)); 
        bRet 
=  TRUE; 
    } 
    
else  
        bRet 
=  FALSE;           //  could not walk the list of threads 
 
    
//  Do not forget to clean up the snapshot object. 
    CloseHandle (hThreadSnap); 
 
    
return  (bRet); 
}

 

 最后为了实现一个简单的管理工具,我用MFC做了个界面,源代码点下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值