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.
argv[0]
as the path to the binary. POSIX says that is should point to the binary, but does not require it and the API allows programs to set it to something else. The end result is, this usually works, but is not reliable. Moreover, even if you have a correct path, the binary may be hardlinked in more than one place. –
Harlamert /proc
pseudo-filesystem. –
Harlamert unlink
is POSIX, not part of the requirement. –
Creed 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?
main
, incidentally. Given that, it only serves to make your example code harder for a newcomer to understand... –
Marmoset -Wall
and -Wextra
switches, emits a warning if I fail to precede int argc
with __attribute__((unused))
in this particular example. The reason is, of course, that argc
is here unused.] –
Allpurpose T**
is not convertible to a const T**
, so it's best not to conflate the two. –
Marmoset 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.
© 2022 - 2024 — McMap. All rights reserved.