小明思考

高性能服务器端计算
posts - 70, comments - 428, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Nothing is impossible:自删除的程序

Posted on 2005-12-07 10:21 小明 阅读(1227) 评论(1)  编辑 收藏 引用 所属分类: Win32
记得以前在程序员杂志上面,看见有人提到这个问题,试了很多种方法,结果是没办法将程序删除。

真的没办法删除自身么?
请运行下面的代码:

#include <windows.h>
#include 
<shlobj.h>

BOOL SelfDelete()
{
  SHELLEXECUTEINFO sei;
  TCHAR szModule [MAX_PATH], szComspec[MAX_PATH], szParams [MAX_PATH];

  
// get file path names:
  if((GetModuleFileName(0,szModule,MAX_PATH)!=0&&
     (GetShortPathName(szModule,szModule,MAX_PATH)
!=0&&
     (GetEnvironmentVariable(
"COMSPEC",szComspec,MAX_PATH)!=0))
  {
    
// set command shell parameters
    lstrcpy(szParams,"/c del ");
    lstrcat(szParams, szModule);
    lstrcat(szParams, 
" > nul");

    
// set struct members
    sei.cbSize       = sizeof(sei);
    sei.hwnd         
= 0;
    sei.lpVerb       
= "Open";
    sei.lpFile       
= szComspec;
    sei.lpParameters 
= szParams;
    sei.lpDirectory  
= 0;
    sei.nShow        
= SW_HIDE;
    sei.fMask        
= SEE_MASK_NOCLOSEPROCESS;

    
// increase resource allocation to program
    SetPriorityClass(GetCurrentProcess(),
                     REALTIME_PRIORITY_CLASS);
    SetThreadPriority(GetCurrentThread(),
                      THREAD_PRIORITY_TIME_CRITICAL);

    
// invoke command shell
    if(ShellExecuteEx(&sei))
    {
      
// suppress command shell process until program exits
      SetPriorityClass(sei.hProcess,IDLE_PRIORITY_CLASS);
      SetProcessPriorityBoost(sei.hProcess,TRUE);

      
// notify explorer shell of deletion
      SHChangeNotify(SHCNE_DELETE,SHCNF_PATH,szModule,0);
      
return TRUE;
    }
    
else // if error, normalize allocation
    {
      SetPriorityClass(GetCurrentProcess(),
                       NORMAL_PRIORITY_CLASS);
      SetThreadPriority(GetCurrentThread(),
                        THREAD_PRIORITY_NORMAL);
    }
  }
  
return FALSE;
}

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     
int       nCmdShow)
{
    
// on program exit
    
// close all handles etc.
    if(!SelfDelete())
    {
      
// add error messaging
    }
    
return 0;    // WinMain exit
  }


程序的思想是通过创建一个另外的进程(ShellExecuteEx),再赋予本进程比较高的权限(SetPriorityClass),
等这个程序退出以后,那个杀进程的进程就可以删除程序了,另外程序通过
SHChangeNotify通知Explorer:程序被删除。

具体API的使用方法请看MSDN.

ps:这个程序是我在老外的网站上找到的,不是我写的。我在VC6,Win2000 Professional上面调试通过

Feedback

# re: Nothing is impossible:自删除的程序  回复  更多评论   

2005-12-16 22:32 by 一笑
REM THIS is bat program, which running in DOS.
del %0

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理