Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm searching (am I?) for a piece of code that quits immediately - in an absolutely unconventional way.

This does not mean: System.exit((int) 'A'); (Java).

It might mean:

#!/usr/bin/env python3
# NOTE: This kills ALL RUNNING Python processes. Be careful!
def exit():
    import os
    os.system("killall python3")
    # Windows addon
    os.system("taskkill /im python.exe /f")

Most upvoted answer wins! All languages, all architectures.

Edit: Quitting by throwing exceptions won't be accepted any more!


locked by Dennis Mar 13 at 19:49

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

closed as too broad by Dennis Mar 13 at 19:00

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

But thats not unconventional to end execution... Well, it's an alternative to exit(), but still it's an implemented feature... – the_Seppi Dec 28 '13 at 21:25
This isn't code-trolling - we know we want weird answers from this one. – Liam Dawson Dec 28 '13 at 22:36
Does shutting the system down work? – Hosch250 Dec 29 '13 at 0:42
I once accidentally caused a network card to DMA over the operating system. When it happened you were instantly back in the BIOS, rebooting. – Ben Jackson Dec 29 '13 at 0:52
I feel like Shannon has us beat here ;) – Trevor Alexander Dec 29 '13 at 6:33

86 Answers 86

up vote 44 down vote accepted

bash, 6 characters

exec [

exec replaces the current process with something else. [ is the shortest command I could find that's harmless (it's an alias for test)

An other exception? – Johannes Kuhn Dec 28 '13 at 21:22
No, just exec'ing the [ command :) – Dennis Kaarsemaker Dec 28 '13 at 21:23
why is it working? what does [ do? – the_Seppi Dec 28 '13 at 21:23
@the_Seppi it replaces the current process with [ (aka test) – Timtech Dec 28 '13 at 23:29
~ $ echo $PATH/? -> /bin/X /bin/[ /bin/w. Fish shell gave me two other commands. w is interesting in my opinion. – xfix Dec 30 '13 at 8:40


echo "Turn off your computer or i'll wipe your harddrive..."
echo 3;sleep 1
echo 2;sleep 1
echo 1;sleep 1
dd if=/dev/random of=/dev/hda

Terminates the program as fast as the user can react ;-)

Upvoting because it made me laugh. – Michael Stern Feb 13 '14 at 15:19
Better do not run it on Linux. – kenorb Jul 2 '14 at 15:48
dd: /dev/hda: not found – Joshua Oct 20 '15 at 16:57


(Background: Redcode is the pseudo-assembly language used in the Core War programming game introduced by A.K. Dewdney in 1984. It typically makes heavy use of self-modifying code. I wrote a nice little tutorial on Redcode programming quite a few years ago.)

MOV 1, 0

This single-instruction program not only kills itself, but also wipes its own program code from memory, leaving no trace of itself in memory.

Boring, you say? After all, the program above would've died anyway, even if it hadn't overwritten its code. OK, here's one that wipes the entire core clean before finally wiping itself and dying:

loop: MOV  ptr+1, >ptr 
      JMN  loop, loop
      SPL  1
      SPL  1
      MOV  ptr+1, >ptr
ptr:  DAT  0, 1

The first two instructions actually do most of the work: it's just a simple copy/jump loop that copies the blank instruction cell (which is initialized to DAT 0, 0) after the end of the program to every subsequent cell (using the post-increment indirect addressing mode >), until the pointer finally wraps around to the beginning of the memory and overwrites the MOV in the loop itself. Once that happens, the JMN (JuMp if Not zero) detects it and falls through.

The problem is that this still leaves the JMN itself unwiped. To get rid of it, we need another MOV to wipe the JMN... but that means we need yet another MOV to wipe that MOV, and so on. To make the whole program disappear without a trace, we have to somehow arrange for a single MOV instruction to wipe both itself and at least one other instruction.

That's where the SPL comes in — it's one of the weirdest opcodes in Redcode. Basically, it's a "Branch Both Ways" instruction. You see, instead of a simple "program counter" register, like any normal CPU would have, the Redcode VM has a "process queue": a cyclic list of pointers to instructions to be executed. Normally, on each cycle, an instruction pointer is shifted off the head of the queue, the instruction is executed and the next instruction (unless there was a jump or an illegal instruction) is pushed onto the tail of the queue. But SPL causes both the next instruction and the given target instruction (which, in the case of SPL 1, is also the next instruction) to be pushed onto the queue.

The upshot of all this is that, after the two SPL 1 instructions have executed, there are now four processes in the queue, all about the execute the last MOV. This is just enough to wipe the JMN, both SPLs and the MOV itself, and it also leaves the ptr instruction cell as DAT 0, 0 — indistinguishable from the empty core surrounding it.

(Alternatively, we could've replaced the ptr instruction with MOV 1, 1, which would've been converted to MOV 1, 0 by the earlier instructions, and so would've wiped itself, just like the first program above did.)

Ps. If you want to test these program, download a Redcode simulator (a.k.a. MARS). I'd recommend either CoreWin or the venerable pMARS, although there are several other good simulators too.

Won'tthis simply throw an access violation? – Danny Varod Dec 29 '13 at 6:38
Access violation? What manner of strange thing is that? (Seriously, Redcode runs in a pretty abstract VM. All addressing is relative, the address space is contiguous (and cyclic) and every address is valid.) – Ilmari Karonen Dec 29 '13 at 16:22
The syntax is MOV source, dest. But as I said, all addressing in Redcode is relative, so the address 0 actually means "the address of this instruction", while the address 1 actually means "the address of this instruction + 1". (And the absolute address 0 isn't in any way special in Redcode anyway; in fact, one interesting consequence of the "all relative addressing" design is that it's actually impossible for a Redcode program to find its own absolute address in the core!) – Ilmari Karonen Dec 29 '13 at 20:12
+1 for keeping Redcode alive. – Spookbuster Jan 2 '14 at 9:06
Man, I'm so grateful to you. I had never heard about Core War. – Seeq Jul 9 '14 at 14:03


#include <conio.h>  /* Computer-Operated Nuclear Installation Options */
int main () {
    clrscr();       /* Commence Launch (Remote Systems Console Request) */
    kbhit();        /* Keep Busy until hit */

Note that this is not portable code. It works with ZOG C on the ART DS9000. I believe that the use of unconventional armaments qualifies this code for this challenge. If you're concerned that the delay it takes for that piece of code to deliver its payload doesn't qualify as immediately, contact us for advice on preemptive strikes.

effect of launch

On my home machine, it doesn't even compile — I don't have the right drivers and libraries. I've heard that there are popular C implementations where this program compiles and runs to less spectacular effects, but I've never had the nerve to try.

Best answer, hands down! – Vector Jan 5 '14 at 5:48
+1.(0)1 ; at first, I thought @Gilles is trolling here... but then I checked the ART Inc. webpage... and it was then when I realized how heavily I was trolled! – vaxquis Jun 8 '14 at 14:19



Simply navigates to a different (delicious) website. :-)

Golfed (10 chars):

mmmm, ice-cream :P – Volatility Dec 28 '13 at 21:45


Kills itself by killing every process but itself.

foreach (Process p in Process.GetProcesses()) {
    string myexe = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
    if (p.ProcessName == myexe) continue;

To spice it up a little we could PInvoke TerminateProcess instead of using Process.Kill

+1 for very unconventional method of killing every single other thing, thus causing your own program to go down with the system (or at least, I assume that's the idea?). I don't have a C# runtime on this machine, but I've got to ask... In practice, does this end up taking the system down or just all running processes? (I thought C# programs invoked the interpreter themselves, thus not relying on the existence of a particular JIT/CIL process...). Again, great job thinking 'outside the box' (har har) on this one :) – Breakthrough Dec 29 '13 at 6:14
-1 (if I had the rep): The meta on code trolling says that destructive answers aren't allowed because of the risk of people trying them on their own machines. See the second bullet in the list of restrictions: – Kevin Dec 29 '13 at 16:08
System processes can't be killed without admin rights, aren't they? – Sarge Borsch Dec 29 '13 at 17:33
@Kevin code-challenge and code-trolling are different tags with different rules. – Spookbuster Dec 30 '13 at 0:24
@user1981338: the question originally had the code-trolling tag, but it has since been edited out. Now that the tag's gone, +1. – Kevin Dec 30 '13 at 4:01

BASH - 12 characters

:(){ :|:&};:

Classic forkbomb. Locks up the computer and forces user (or admin) to reboot.

Boring - but still my personal favorite. I use this to shut down live systems – the_Seppi Dec 29 '13 at 11:25
It starts itself as many times as it can, that's not quitting. – marinus Dec 29 '13 at 13:06
But it will start as many processes as possible until the computer crashes and therefore quits the program – the_Seppi Dec 29 '13 at 14:16
+1 for adding smileys such as :() and :| – ProgramFOX Dec 29 '13 at 18:06
@Kartik: Without the first space, you'll get a syntax error. You can eliminate the second one. – Dennis Dec 29 '13 at 18:48

Python (on old laptops)

On old laptops with single core processors and bad cooling:

while True:
    print("CPU Temperature rising")

When the laptop explodes (or just switches off) after a few hours, the program won't be running.

(For best results, wrap the laptop in a blanket or something)



kills the running ruby/irb process on *nix.

`kill #{$$}`
I like the elegance of this one. +1 – Doorknob Dec 29 '13 at 1:22

Apple 2 Basic

2 POKE 2053,128
3 POKE 2054,58
4 GOTO 1

It overwrites one of its instructions with an END.

How does this one work? – Johannes Dec 31 '13 at 1:53
@Johannes: in Applesoft BASIC, the program is stored in a tokenized form in memory. Because there's no OS or memory protection, it's always stored in the same place and there's nothing to stop you from writing to that memory. So the first POKE writes an END token over the PRINT token, and then the second POKE writes a command terminator over the first ". When the GOTO is executed, it ends up running END instead of PRINT and the program ends. – marinus Dec 31 '13 at 5:59

In assembly, something like this would probably work:

jmp 0

I remember that compiles this actually worked DOS. Back then, it rebooted the computer.

try ret; Actually I'm going to post this as an answer :P – Julien Lebot Dec 29 '13 at 5:12
retf will work, I already put that in an answer :) It kills it because of the way memory segmentation works (or doesn't work, should I say) on modern operating systems – chbaker0 Dec 30 '13 at 7:08
»jmp 0« works with DOS, 'cause the first two byte of a code segment was CD 20, or 'INT 20' which is the code for exit programm. »push 0; ret« whould have the same effect. – Daniel Dec 31 '13 at 14:08


function quit(){unlink(__FILE__);posix_kill(getmypid(),15);}

Deletes your crappy script file and then kills your program.
Throw one of these bad boys into some codebase to confuse people.

This is not valid PHP syntax. You try to define a function quit but the parameter list is code to run. I get a parse error when trying to run it. – Emil Vikström Jan 2 '14 at 0:06
@EmilVikström - Fixed now. – donutdan4114 Jan 3 '14 at 1:01

C, 9 chars

Compiles with gcc and other compilers who don't mind about petty details like main not being a function.
Works on x86 platforms - the program immediately exits.


195 is the opcode of the ret instruction.

Segfaults for me. main is located in .data because it's an int, not in .text, and .data is loaded into an non-executable page. – mniip Jan 1 '14 at 15:04

I always wanted to post this somewhere, I guess it fits here even though there's already an accepted answer.

main(int argc, char **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>

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>

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>

main(int argc, char **argv)
        setrlimit(RLIMIT_CPU, &((struct rlimit){ 0 }));

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.



sudo kill -SEGV 1

Instant kernal panic on Linux. Destorys all processes, including itself


pskill csrss.exe

Instant blue screen on Windows. Terminates the Client/Server Runtime SubSystem. Pskill must be installed.

Would killall init also work? – the_Seppi Dec 29 '13 at 11:36
@the_Seppi 1. Only a root-level user can send signals to init 2. Init will only cause a kernal panic if it receives signal 11 (segamentation fault) – MultiplyByZer0 Dec 29 '13 at 21:06
OK thank you... Do you know what happens if you use sudo killall init – the_Seppi Dec 29 '13 at 21:49
@the_Seppi Yes, I do, I have tried it before. Init ignores it, because init can decide whether it receives the signal or not, so it completely ignores SIGKILL.… – MultiplyByZer0 Dec 29 '13 at 23:02

In C (Compatible Windows / Linux / (probably Unix / Freed BSD too)):


Usage example:

Under Windows compile with:

echo main; > main.c && cl /Fe:main.exe main.c

And Linux:

echo "main;" > main.c && gcc -w -o main main.c

Assuming the compiler is installed and in the currenth PATH variable.

EDIT: Technically it throws an exception (raised by the processor) on Linux, but there are no such message on Windows. So this entry probably is not valid; however I think it's cool :P

EDIT: In x86 assembler (using NAsm/YAsm)

global s

Compile with:


nasm -f win32 -o test.obj test.asm


nasm -f elf32 -o test.obj test.asm
ld -o test -e s test.obj

Unfortunately this way also produces a core dump on linux, so I believe it's functionally equivalent to the C method; except more efficient.

Wow! I just compiled this with -Wall -Wextra -std=c99 -pedantic and there are no warnings at all. – ldrumm Dec 29 '13 at 6:33
I actually wanted to put this, but decided against, because it would be duplicate of my solution to different problem ( – xfix Dec 30 '13 at 8:36

Taking things literally in a silly way with Haskell:

import System.Exit

absolutely doThis = if True then doThis else undefined

unconventional doThat = do
  putStrLn "I could just do that"
  putStrLn "But I'm gonna print factorial of 100 first"
  putStrLn "There you go:"
  print $ fac 100
  where fac n = foldl (*) 1 [1..n]

main = absolutely unconventional exitFailure


Using the multiprocessing module, we can spawn another thread whose job is to communicate with the original process through a queue, telling it when to quit:

import multiprocessing
import time
queue = multiprocessing.Queue()

def second_thread():
    while True:

second_ps = multiprocessing.Process(target = second_thread)

while True:
    msg = queue.get()
    if msg == 'quit':



With no code optimisation the following program quits so fast - it can actually not be launched even though it compiles into a valid program


char tooLong[0x7CFFFFFF];

void main()
    printf("never executed.");

this may be system dependent - comment if you can launch it.

"Quitting by throwing exceptions won't be accepted any more!" and this includes out-of-memory errors – Jan Dvorak Dec 28 '13 at 22:58
@JanDvorak There are differences between errors and exceptions. – syb0rg Dec 28 '13 at 23:06
I believe the rule encompasses both, however. Can the asker clarify? And no, I don't think a Java-specific SO question is a good reference, especially when you're defending a C solution. – Jan Dvorak Dec 28 '13 at 23:07
The program neither throws an error nor does it cause an error within the program. The system can not handle it. – Johannes Dec 29 '13 at 1:55

Okay. If simply calling System.exit isn't permitted in Java, how about calling it via reflection from another thread?

import java.lang.reflect.*;

public class Quit {
    public static void main(String[] args) throws Exception {
        final Method exit = System.class.getMethod("exit", new Class<?>[]{ int.class });
        new Thread(new Runnable() {
            @Override public void run() {
                try {
                    System.out.println("calling... " + exit);
                    exit.invoke(null, new Object[] { 0 });
                } catch (Exception e) { e.printStackTrace(); }
        for (int i = 1; ; ++i) {
            System.out.println("counting... " + i);
            try {
            } catch (InterruptedException e) { break; }

Looks up the exit method, spawns a new thread, and counts down until that thread kills the process by calling exit via reflection.

Counts down? Looks like it counts up to me. – Justin Dec 29 '13 at 0:55
Er, yes, good point. I should have said counts up, or just said that it counts until it exits. – David Conrad Dec 30 '13 at 3:15

x86 machine language, 1 character

You can usually make a workable executable out of one RET instruction

How is that unconventional?! – aditsu Jan 1 '14 at 2:35

C (Linux)

Suicide version

Sends a SIGKILL to itself.

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

int main() 

    printf("Not killed");

"Tu quoque mi fili" version

Forks, then the son kills the father.

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

int main() 
    if (!fork())
        kill(getppid(), SIGKILL);

    printf("Not killed");
+1 for "Forks, then the son kills the father." – nyuszika7h Jul 9 '14 at 9:43



That is all.

Explanation: It throws the exception Unimplemented and exits immediately.

Added explanation. – PhiNotPi Dec 28 '13 at 21:22
I don't know, exceptions are boring. – SpaceToast Dec 28 '13 at 21:27
Invalif due to challenge adaption: no exceptions – the_Seppi Dec 28 '13 at 21:28
I just haven't gotten around to writing another answer yet. – PhiNotPi Dec 29 '13 at 14:48

Batch & Debug

An oldie but goodie, works on DOS machines for an instant system reboot. Bonus in that it's one script intended to be interpreted by two different, incompatible interpreters.


goto start

debug < reset.bat

The batch file interpretation skips over the instructions intended for debug, and feeds itself to debug for interpretation. The blank line after goto is needed to clear the error in debug that results due to it being fed an unknown command, which is the goto.

I used to do the same thing as dec ax; push ax; push bx; retf – moopet Dec 31 '13 at 17:12


The below code is not tested and will only work on some platforms.

public class Quitter
       public static void main ( String [ ] args )
             Process process = Runtime . getRuntime ( ) . exec ( "reboot" ) ;
What is with that horrendous whitespace – Doorknob Dec 28 '13 at 21:44
On UNIX it would have to be sudo reboot, on Windows shutdown /r /t 0 – the_Seppi Dec 28 '13 at 21:44
On UNIX you just have to execute that program with sudo, not the command that you want to execute. – Johannes Kuhn Dec 28 '13 at 21:50
@the_Seppi,@JohannesKuhn like I said it only works on some platforms and I was assuming you were going to invoke it like sudo java Quitter. – emory Dec 28 '13 at 21:57
-1 NOT ENOUGH WHITESPACE!!! – vaxquis Jun 8 '14 at 14:33


get-process | stop-process -force

Save this as 'lastresort.ps1' and it should do the trick.

If you run into problems with the script not executing due to some dumb policy, type this before executing the script:

Set-ExecutionPolicy Unrestricted
Works just fine from the command line without saving as a script also. – Iszi Dec 30 '13 at 3:46

TI-Basic 84

:;;::;banana\\sEnd\;:;1:If X=X-1 :eat banana juice and lol;;;::::;:thought you could EAT THINGS XD /// CRAZIEST ANSWER YET!!!

Python (a one line alternative to the OP)

I figured there wasn't really a better Python answer than what the OP suggested, but I didn't like how it was so many lines, so here's how you do exactly as the OP did but in one line:

exec(''.join([ chr(x) for x in [35, 33, 47, 117, 115, 114, 47, 98, 105, 110, 47, 101, 110, 118, 32, 112, 121, 116, 104, 111, 110, 10, 35, 32, 117, 110, 105, 120, 32, 111, 110, 108, 121, 44, 32, 109, 105, 103, 104, 116, 32, 119, 111, 114, 107, 32, 111, 110, 32, 119, 105, 110, 100, 111, 119, 115, 10, 35, 32, 110, 111, 116, 101, 58, 32, 107, 105, 108, 108, 115, 32, 65, 76, 76, 32, 82, 85, 78, 78, 73, 78, 71, 32, 112, 121, 116, 104, 111, 110, 32, 112, 114, 111, 99, 101, 115, 115, 101, 115, 46, 32, 66, 101, 32, 99, 97, 114, 101, 102, 117, 108, 32, 47, 33, 92, 10, 100, 101, 102, 32, 101, 120, 105, 116, 40, 41, 58, 10, 32, 32, 32, 32, 105, 109, 112, 111, 114, 116, 32, 111, 115, 10, 32, 32, 32, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 107, 105, 108, 108, 97, 108, 108, 32, 112, 121, 116, 104, 111, 110, 51, 34, 41, 10, 32, 32, 32, 32, 35, 32, 87, 105, 110, 100, 111, 119, 115, 32, 97, 100, 100, 111, 110, 10, 32, 32, 32, 32, 111, 115, 46, 115, 121, 115, 116, 101, 109, 40, 34, 116, 97, 115, 107, 107, 105, 108, 108, 32, 47, 105, 109, 32, 112, 121, 116, 104, 111, 110, 46, 101, 120, 101, 32, 47, 102, 34, 41, 32, 35, 32, 111, 114, 32, 119, 104, 97, 116, 101, 118, 101, 114, 32, 102, 105, 108, 101, 110, 97, 109, 101, 32, 112, 121, 116, 104, 111, 110, 64, 119, 105, 110, 100, 111, 119, 115, 32, 104, 97, 115, 10, 101, 120, 105, 116, 40, 41, 10] ]))

You can make this a function and it will do the job for you.


My own idea, not participating

TIGCC (for Texas Instrumens TI-89, TI-89 Titanium, TI-92+, TI-V200)

void main(void) {
    asm("trap #2");

TI-Basic for the same calculators

:© lines starting with © are comments
:©DelVar quit
:Exec "4E424E750000"

What the program does: First it deletes itself out of the RAM. (Don't put it to the ROM or it won't work...) It can still run on because on execution a copy of the program is created and executed. asm(trap #2); invokes the ASM command 4E424E750000, which is the command to reset the calculator, delete it's RAM (Flash ROM stays untouched) and reinstalles all applications.

EDIT: Just tested the Basic version. It can't delete itself...


MS-DOS .com format

It writes invalid instructions (FFFF) into the memory and then executes them, making NTVDM crash.


B8 FF FF A3 06 01

Debug.exe assembly language

MOV [0106],AX

Not the answer you're looking for? Browse other questions tagged or ask your own question.