了解C++中的自删除程序
Understanding a self-deleting program in C++
有一个自删除程序
#include <windows.h>
#include <stdio.h>
void main(int argc, char* argv[])
{
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
if (argc == 1)
{
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
CopyFile(argv[0], "1.exe", FALSE);
MoveFile(argv[0], "2.exe");
CreateFile("1.exe", 0, FILE_SHARE_READ, &sa,
OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL);
CreateProcess(NULL, "1.exe x", NULL, NULL,
TRUE, 0, NULL, NULL, &si, &pi);
}
else if (argc == 2)
{
while(!DeleteFile("2.exe"));
CreateProcess(NULL, "net", NULL, NULL, TRUE,
DEBUG_ONLY_THIS_PROCESS, NULL, NULL, &si, &pi);
}
}
如果我删除这个:CreateProcess(NULL, "net", NULL, NULL, TRUE, DEBUG_ONLY_THIS_PROCESS, NULL, NULL, &si, &pi);
它行不通。
谁能向我解释一下它是如何工作的?
这是一个解释(据我了解)
void main(int argc, char* argv[])
{
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
if (argc == 1)
{
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
// Make a copy of ourselves which we'll use to delete the version we were run from
CopyFile(argv[0], "1.exe", FALSE);
// Rename the running copy of ourself to another name
MoveFile(argv[0], "2.exe");
// Make sure we delete the copy of ourselves that's going to delete us when we die
CreateFile("1.exe", 0, FILE_SHARE_READ, &sa, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL);
// Invoke the process that will delete us
// allowing it to inherit the handle we just created above.
CreateProcess(NULL, "1.exe x", NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
}
else if (argc == 2)
{
// Wait for the original program to die (deleting us and closing a handle), then delete it
while(!DeleteFile("2.exe"));
// Launch a child process which will inherit our file handles
// -- This keeps the file handle with FILE_FLAG_DELETE_ON_CLOSE (which we inherited) alive beyond our lifetime
// this allowing us to be deleted after we've died and our own handle is closed.
CreateProcess(NULL, "notepad", NULL, NULL, TRUE, DEBUG_ONLY_THIS_PROCESS, NULL, NULL, &si, &pi);
}
}
相关文章:
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 在unique_ptr<>中使用自定义删除程序 (curl_formfree())
- 如何从 CLion 的运行窗口中删除程序项目路径
- shared_ptr的删除程序是否存储在自定义分配器分配的内存中?
- 用于unique_ptr的有状态自定义删除程序
- 为什么unique_ptr不能阻止自定义删除程序的切片?
- std::shared_ptr 在空指针上调用非默认删除程序
- std::unique_ptr 和自定义删除程序
- 如何避免多个删除程序 lambda
- 如何使用lambda和函数作为unique_ptr的自定义删除程序
- std::unique_ptr,自定义删除程序和类型更改
- shared_ptr<EVP_PKEY> EVP_PKEY_free作为自定义删除程序会导致堆损坏
- 使用自定义删除程序返回unique_ptr的 nullptr 失败
- 对 Direct3D11 对象上使用 std::shared_ptr 的自定义删除程序
- 为shared_ptr但遇到错误指定自定义删除程序
- 为什么unique_ptr无法推断出删除程序的类型?
- 删除程序的调用上下文
- unique_ptr、自定义删除程序和零法则
- std::在C++中设置删除程序不起作用
- 带有自定义删除程序错误的 c++ 唯一指针