I always wanted to post this somewhere, I guess it fits here even though there's already an accepted answer.
int main(int argc, char **argv) { revoke(*argv); } This works on any post 4.3BSD system and others that implement revoke in the same way. Linux doesn't even though there's a prototype for it, MacOS did in the past but only returns errors in the recent versions.
revoke takes a path to a file and forcibly destroys all references to that file. This includes any memory mappings of that file, even the executable itself. Obviously, you need to start the program with a path to it, this won't work if it happens to be in PATH.
A variation of this that should work on most unix-like systems is:
#include <sys/mman.h> #include <inttypes.h> #include <unistd.h> int main(int argc, char **argv) { intptr_t ps = getpagesize(); munmap((void *)(((intptr_t)main)&~(ps - 1)), ps); } We just unmap the page that maps main so that when the call to munmap returns, it doesn't have anywhere to return to. There's a slight chance that the the function call to munmap is just on a page boundary and the return will succeed, so to be perfectly sure this works, we probably have to attempt to unmap two pages first.
And of course, a variation on the same theme:
#include <sys/mman.h> #include <inttypes.h> #include <unistd.h> int main(int argc, char **argv) { intptr_t ps = getpagesize(); munmap((void *)(((intptr_t)&ps)&~(ps - 1)), ps); } Just unmap the stack so that we don't have anywhere to return to. Same caveat as unmapping main - we might need to unmap two pages, except that we have to remember that the stack probably grows down (unless you're on PA-RISC or some other strange architecture like that).
Another way to pull the rug from under your own feet:
#include <sys/resource.h> int main(int argc, char **argv) { setrlimit(RLIMIT_CPU, &((struct rlimit){ 0 })); while(1); } It is operating system dependent with how the system handles a 0 second cpu limit and how often accounting for cpu time is done. MacOS kills the process immediately, Linux requires the while loop, another system I tried didn't do anything even with a one second limit and a while loop, I didn't debug further.