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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With