Question

Is it possible to write a program in C that upon execution deletes itself (the binary) and then terminates successfully. If so, what's the easiest way of doing this?

Was it helpful?

Solution

Yes.

#include <unistd.h>
int main(int argc, char* argv[])
{
  return unlink(argv[0]);
}

(Tested and works.)

Note that if argv[0] does not point to the binary (rewritten by caller) this will not work. Similarly if run through a symlink then the symlink, not the binary, will be deleted.

Also if the file has multiple hard links, only the called link will be removed.

OTHER TIPS

I do not know that one can conveniently do it in a truly platform-independent way, but you didn't specify platform independence, so try the following, Linux-style code:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv) {
    printf("Read carefully!  You cannot print this message again.\n");
    return unlink(argv[0]);
}

How close is that to what you want?

If you operating system allows a running program to delete its own binary, then just look for the API for file deletion, or execute a corresponding system() command.

If the OS doesn't allow this, your program (let's call it A) could construct another binary, containing another program (let's call it B). Then, A would immediately quit.

Program B would have a single loop checking if A is still running and as soon as A quits, B would erase A's binary.

You could try to just delete the executable in the program (FILE* and stuff)... but seeing as that executable is what's being run it might not work. I see it like eating yourself, and as far as I know it's not possible, but you could certainly give it a try using the method I mentioned above.

I think it is dependent on the platform you are using. Basically, once the executable is loaded, any subsequent change to the binary does not affect the running program. In Unix, this is the case, and you can use the unlink system call.

I am not sure whether this is true on Windows or not. It may not be allowed to delete the executable image. You can try the DeleteFile() api in Windows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top