2012-04-25 42 views
7

有一個自我刪除程序瞭解在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); 它不能正常工作。
任何人都可以向我解釋它是如何工作的?

+0

如果將它轉換爲使用wmain和運行unicode的,這是行不通的......奇怪。 – Benj 2012-04-25 16:34:23

+0

因爲文件名字符串爲ASCII編碼。也許你可以圍繞stirng加_T()。 – pl8787 2012-04-25 16:38:27

+0

哈哈,葉我這樣做,它沒有編制,我的意思是它在運行時不工作。 – Benj 2012-04-25 16:39:05

回答

8

這裏有一個解釋(據我所知的東西)

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); 
    } 
} 
+0

您的意思是CreatProcess保留這個程序的句柄?但我仍然不明白它是如何工作的。這是否意味着如果我刪除它,沒有足夠的時間讓程序刪除它自己? – pl8787 2012-04-25 16:42:58

+1

如果FILE_FLAG_DELETE_ON_CLOSE句柄太早關閉,則刪除將失敗,因爲1.exe進程仍在運行。通過啓動繼承該句柄的子項,1.exe的句柄關閉,允許在孩子關閉時刪除它。 – Benj 2012-04-25 16:50:26

+0

非常感謝〜我想我明白你的意思。 – pl8787 2012-04-25 16:53:03