C/C++
//VC-ConsoleWithApi
#include
//提权函数
void RaiseToDebugP()
{
HANDLE hToken;
HANDLE hProcess = GetCurrentProcess();
if ( OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
{
TOKEN_PRIVILEGES tkp;
if ( LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid) )
{
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
BOOL bREt = AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, 0) ;
}
CloseHandle(hToken);
}
}
BOOL OccupyFile( LPCTSTR lpFileName )
{
BOOL bRet;
//提升自身权限
RaiseToDebugP();
//打开一个pid为4的进程,只要是存在的进程,都可以
HANDLE hProcess = OpenProcess( PROCESS_DUP_HANDLE, FALSE, 4); // 4为system进程号
if ( hProcess == NULL )
{
return FALSE;
}
HANDLE hFile;
HANDLE hTargetHandle;
//以独占模式打开目标文件
hFile = CreateFile( lpFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, NULL);
if ( hFile == INVALID_HANDLE_VALUE )
{
CloseHandle( hProcess );
return FALSE;
}
//把文件句柄复制到pid=4的进程中去,这样,只要pid=4的进程不退出,谁也动不了目标文件
bRet = DuplicateHandle( GetCurrentProcess(), hFile, hProcess, &hTargetHandle,
0, FALSE, DUPLICATE_SAME_ACCESS|DUPLICATE_CLOSE_SOURCE);
CloseHandle( hProcess );
return bRet;
}
//入口函数
int main()
{
OccupyFile("D:\\Program Files\\工具软件\\任务管理.exe");
return 0;
}