Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a self-destructive program in C?

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?

like image 483
Alex Coplan Avatar asked Apr 01 '12 14:04

Alex Coplan


3 Answers

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.

like image 175
blueshift Avatar answered Oct 22 '22 07:10

blueshift


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?

like image 38
thb Avatar answered Oct 22 '22 05:10

thb


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.

like image 2
Imp Avatar answered Oct 22 '22 07:10

Imp