How to write a program in C++ such that it will delete itself after execution?

前端 未结 7 1018
醉话见心
醉话见心 2020-12-14 01:35

How to write a program in C++ such that it will delete itself after execution ?

相关标签:
7条回答
  • 2020-12-14 01:58

    Here is the code in C which will delete the executable after execution.

    #include <Windows.h>
    #include <strsafe.h>
    
    #define SELF_REMOVE_STRING  TEXT("cmd.exe /C ping 1.1.1.1 -n 1 -w 3000 > Nul & Del /f /q \"%s\"")
    
    void DelMe()
    {
        TCHAR szModuleName[MAX_PATH];
        TCHAR szCmd[2 * MAX_PATH];
        STARTUPINFO si = {0};
        PROCESS_INFORMATION pi = {0};
    
        GetModuleFileName(NULL, szModuleName, MAX_PATH);
    
        StringCbPrintf(szCmd, 2 * MAX_PATH, SELF_REMOVE_STRING, szModuleName);
    
        CreateProcess(NULL, szCmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi);
    
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }
    
    void main()
    {
        /* Do what you need */
    
        /* Call this function at the very end of your program to delete itself */
        DelMe();
    }
    
    0 讨论(0)
  • 2020-12-14 01:58

    std::remove(argv[0]) before return in main can do it.

    0 讨论(0)
  • 2020-12-14 02:02

    Some Methods

    You could also, use some kind of Scheduled Task...

    0 讨论(0)
  • 2020-12-14 02:02

    For Windows try this. It is basically launching a .bat file that loops until the destruction is sucessful:

    http://www.codeproject.com/Articles/4027/Writing-a-self-destructing-exe-file

    0 讨论(0)
  • 2020-12-14 02:03

    However there is a way to delete the file by itself after execution because every Uninstaller unistalls the software which was installed by it & also deletes the last remaining file i.e., itself such that no files will be remaining in our Hard Disk except some Registry Entries irrespective of the platform it has been installed.

    0 讨论(0)
  • 2020-12-14 02:04

    On Unix, just call unlink(2) on the executable.

    On Windows, you need a second process to help you. The response from st0le seems to be for unlinking a DLL, but for an executable, you would need to start a second process or use an existing process, and then terminate your executable and have the second process do the deletion.

    A very simple approach would be to use cmd.exe to help.

    An speculative approach that uses any other process could be to allocate some memory in another process and put the filename you want to delete there, then use CreateRemoteThread() to create a suspended thread in the remote process with an entry point of DeleteFile with an argument of a pointer to the memory you allocated. Then exit your process, the thread suspend count should decrement and then DeleteFile should be called to delete your file.

    Issues: Memory leak in the remote process, messy.

    An easier way might just be to have a supporting DLL using the techniques from st0le's answer.

    0 讨论(0)
提交回复
热议问题