程序通过创建线程实现删除自身(转)

@echo   off
loop
del access.exe
if exist access.exe
goto loop
del DelMe.bat

下面用C/C++语言表示创建DelMe.bat文件

FILE *pFile=NULL;
pFile
=fopen("DelMe.bat","w");
if(pFile==NULL)
{
return;
}
fputs(
"@echo off\n",pFile);
fputs(
"loop\n",pFile);
fputs(
"del access.exe\n",pFile);
fputs(
"if exist access.exe\n",pFile);
fputs(
"goto loop\n",pFile);
fputs(
"del DelMe.bat\n",pFile);

再通过API函数执行DelMe.bat文件

下面通过创建线程实现程序删除自身


#include <windows.h>
BOOL SelfDelete();
//----------------------------------------------------------------
int main()
{
SelfDelete();
exit(
0);
return 0;
}
//---------------------------------------------------------------
BOOL SelfDelete()
{
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");
lstrcat(szComspec, szParams);


// set struct members
STARTUPINFO si={0};
PROCESS_INFORMATION pi
={0};
si.cb
= sizeof(si);
si.dwFlags
= STARTF_USESHOWWINDOW;
si.wShowWindow
= SW_HIDE;

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

// invoke command shell
if(CreateProcess(0, szComspec, 0, 0, 0,CREATE_SUSPENDED|
DETACHED_PROCESS,
0, 0, &si, &pi))
{
// suppress command shell process until program exits
SetPriorityClass(pi.hProcess,IDLE_PRIORITY_CLASS);
SetThreadPriority(pi.hThread,THREAD_PRIORITY_IDLE);

// resume shell process with new low priority
ResumeThread(pi.hThread);

// everything seemed to work
return TRUE;
}
else // if error, normalize allocation
{
SetPriorityClass(GetCurrentProcess(),
NORMAL_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),
THREAD_PRIORITY_NORMAL);
}
}
return FALSE;
}


posted @ 2011-09-03 22:41  zhjb616  阅读(246)  评论(0编辑  收藏  举报