ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자기자신을 삭제하는 실행파일 만들기
    Programming/WINAPI 2007. 12. 4. 22:53

    uninstall시 unsintall.exe 자기 자신은 어떻게 지우는걸까??

    방법이 여러가지 있는것으로 알고 있습니다만..
    최대한 단순한 방법이라고 생각하고 올려봅니다.

    지금 소개되는 방법은
    실행파일내부에서 실행파일을 삭제하는 batch파일을 만들어
    그 batch파일이 실행파일을 삭제하도록 하는 방법입니다.

    ────────────────────────────────────────────────────


    #include <windows.h>
    
    void Kill()
    {
         FILE *fp = NULL;
        // batch파일명
         char* killer = "killfile.bat";
        // 실행파일명
         char* thisFile = "SelfDelete.exe";
         char szBatFile[256];
    
         // batch파일을 생성합니다.
         fp = fopen(killer,"wt");
         if(fp == NULL)
         {
              puts("파일생성 실패");
              return;
         }
     
         // batch파일에 실행할 내용 작성
         wsprintf(szBatFile,
              ":Repeat      \r\n"   
              "del /f /s /q %s    \r\n"
              "if exist \"%s\" goto Repeat \r\n"
              "del /s /q %s     \r\n", 
              thisFile, thisFile, killer); 
    
         fwrite(szBatFile, strlen(szBatFile), 1, fp);
         fclose(fp);
    
         // batch파일을 실행합니다.
         ShellExecute(NULL,"open",killer,NULL,NULL,0);  
    }
    
    
    void main()
    {
         Kill();
    }
    

    ────────────────────────────────────────────────────
     위의 코드에서 중요한건 batch파일의 내용인데 코드를 보면
         wsprintf(szBatFile,
             
    ":Repeat      \r\n"  
              "del /f /s /q %s    \r\n"
              "if exist \"%s\" goto Repeat \r\n"
              "del /s /q %s     \r\n",
              thisFile, thisFile, killer);

    :Repeat 
    del /f /s /q SelfDelete.exe
    if exist SelfDelete.exe goto Repeat
    del /s /q killfile.bat

    먼저 SelfDelete.exe를 삭제를 합니다.
    그리고 나서 SelfDelete.exe가 있으면 Repeat로 다시 갑니다.
    이렇게 계속 SelfDelete.exe가 존재하지 않을때까지 삭제명령을 계속 내립니다.
    그리고 나서 SelfDelete.exe가 삭제가 되면 killfile.bat 을 삭제합니다.


    위에 존재하지 않을때까지라는 말은 결국 실행파일의 종료되어 파일을 삭제할 수 있는 때가 되는 것입니다.






    그리고 아래는 batch파일에서 사용한 del 실행인자 설명입니다.
    -------------------------------------------------------------------------
      /F            읽기 전용 파일을 강제로 삭제합니다.
      /S            지정된 파일을 모든 하위 디렉터리에서 삭제합니다.
      /Q            조용한 모드, 글로벌 와일드카드에서 삭제해도 묻지 않습니다.
    -------------------------------------------------------------------------


    코드프로젝트에서 비슷한 내용이 있어 링크를 걸어요..
    코드프로젝트 : Self Deleting executables (http://www.codeproject.com/KB/winsdk/selfdel.aspx)

Designed by Tistory.