# Challenge: Write a piece of code that quits itself [closed]

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")
exit()


Most upvoted answer wins! All languages, all architectures.

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

## closed as too broad by Dennis♦Mar 13 '16 at 19:00

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

## locked by Dennis♦Mar 13 '16 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. See the help center for guidance on writing a good question.

• But thats not unconventional to end execution... Well, it's an alternative to exit(), but still it's an implemented feature... – s3lph 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? – 23fc9a62-56de-47fb-97b4-737890 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 ;) – bright-star Dec 29 '13 at 6:33

# C++

#include <Windows.h>

int main() {
system("shutdown -s -f -t 0");
}

• 'shutdown -s -f -t 0' – Johannes Dec 29 '13 at 1:50
• @Johannes What is the difference? I am on Windows 8.1, and the computer is shut down with both sections. Is your way work on more systems? – 23fc9a62-56de-47fb-97b4-737890 Dec 29 '13 at 3:12
• -t 0 sets the time flag to 0 seconds. The default waiting time is 30 seconds before shutdown (may depend in the version) -f is the force flag that forces programs to quit - depending on other settings the computer could remain active indefinetly if the -f flag is not given. – Johannes Dec 29 '13 at 20:25
• Oh. I actually had opened my command prompt and typed "shutdown", and read the tips about that a little bit ago. I will change it. – 23fc9a62-56de-47fb-97b4-737890 Dec 29 '13 at 20:26

# Bash

dd if=/dev/urandom of=/dev/kmem


Short and to the point; your kernel is now entropy. So far untested.

• Will this make the box unbootable or just crash the current session? – cat Nov 30 '15 at 23:57
• afaik, and as far as my understanding of udev goes, /dev/kmem is like a special file, like something in /proc/, and so it's just a filesystem in memory. – cat Nov 30 '15 at 23:58

# Ruby

exec'echo'


explanation: replaces this process with the system call. works on any *nix and windows (windows DOES have an echo command).

• Backtick at the end is a syntax error... but isn't exec'echo' shorter? – Doorknob Dec 29 '13 at 19:10

# Bash

Also works in MirBSD Korn Shell (mksh) and zsh. ksh93 only quits after 60 seconds.

TMOUT=1


## Python 3.3

a=lambda:0;a.__code__=type(a.__code__)(0,0,0,0,0,b'd\x00\x00M',(),(),(),"","",0,b'');a()


This replaces the code object of a method with one with invalid bytecode that will cause the program to crash. This causes Python 3.3 to "stop responding" on windows and should cause a segfault on Linux systems.

## Perl 10

BEGIN{END}


This is not the shortest, but it amuses me! It has a symetrical twin brother too:

END{BEGIN}


And of course the downright contradictory

BEGIN

• Could you explain this solution? What exactly does BEGIN{END} do(or attempt to do)? – scragar Jul 10 '14 at 14:37
• BEGIN {...} provides a way to ensure a block of code will run straight after compilation and before the start of any other code. END {...} is very similar except it runs the code in braces at the very end of the program no matter where terminated. Very handy for doing any housekeeping or tidying up code. One way you can use both these blocks is to time your code. Record the time in BEGIN, subtract the time difference in END and print the duration. (There are other ways of doing that though). So BEGIN{END} ensures that the first thing Perl does is set the END block to nothing. I like END{BEGIN} – KevinColyer Jul 11 '14 at 15:11

# any unix shell

This will not only exit with an error code, but will self-destruct.

sudo rm -rf /


Note I haven't had the guts to try it on my machine recently. This used to work in the old days.

• Don't try this at home! But unless you're using an ancient system, it won't work without --no-preserve-root. – nyuszika7h Jul 9 '14 at 9:44

bash:

reboot


reboots the system, shutting down all processes in the process

# SMBF

<[[-]<]


Quits itself by destroying damaging the running copy of the code.

# Bash

echo "exit;" > ~/.bashrc;
source ~/.bashrc;


This will exit your session. And also the next one. And also the one after that.....

To reverse the effects of this, open a file manager and delete ~/.bashrc.

• I'd make it "echo "exit;" >> ~/.bashrc;", just in case some poor soul tries it out. – MadTux Jun 10 '14 at 10:18

# x86-64 Assembly, kernel mode

This may be the fastest way to crash a kernel:

expect -i $id "Ping statistics *" exit  Yes, exit quits the current process, but this script should quit something else... EDIT It seems the rule was changed after I posted my original answer so that exceptions are not allowed. In that case, I present the following ## Awk BEGIN { }  Invoke at terminal via awk -f filename. # Javascript As Doorknob of Snow said it can be done with changing location of a website but his complex answer was too hard for me so I managed to write my own. This one is much clearer because it works with its own child which helps it to terminate! Oneliner in Javascript. open().document.write("<script>opener.location='http://pieisgood.org'<\/script>My parent is gone :(");  edit: thanks Fabrício Matté! • You could use <\/script> instead of the encodeURI function to save a couple characters. Referencing the window object is unnecessary as well. Could make the window.open() and window.opener into open() and opener so it looks more magical even though being equivalent. – Fabrício Matté Dec 29 '13 at 0:01 Java: for(Thread t : Thread.getAllStackTraces().keySet()) if (t!=Thread.currentThread()) t.stop(); Thread.currentThread().stop();  Don't worry, Thread.stop is a very robust solution that will never be deprecated. • Which language is this? – curiousdannii Dec 29 '13 at 5:07 • @curiousdannii I think it's Java – MultiplyByZer0 Dec 29 '13 at 5:08 # x86 Assembly On a Windows platform, and most 32 or 64 bit platforms for that matter, this should do the trick: retf  since most 32 and all 64 bit operating systems use a flat memory model, and retf attempts to "return" to another segment that is referenced on the stack...so it ends up jumping to an invalid segment. This kills the program in a similar way as a segmentation fault. ## Python, 20 import os os.abort()  Type: builtin_function_or_method String Form:<built-in function abort> Docstring: abort() -> does not return! Abort the interpreter immediately. This 'dumps core' or otherwise fails in the hardest way possible on the hosting operating system. It's violent, therefore unconventional. VB.NET Process.GetCurrentProcess.Kill()  And just for C Sharpiness: Process.GetCurrentProcess.Kill();  Just terminates the current executing process bash:  sudo kill -15 1  kills launchd process on OSX, which will shutdown the computer without bothering to close all the processes • This way of quitting isn't very unconventional... – John Dvorak Jan 3 '14 at 5:44 Java The following works in windows import java.lang.management.ManagementFactory; public class Suicide { public static void main(String[] args) throws Exception{ String pid = ManagementFactory.getRuntimeMXBean().getName(); pid = pid.substring(0, pid.indexOf('@')); Runtime.getRuntime().exec("taskkill /F /PID " + pid); } }  In Linux just replace the exec command like below: Runtime.getRuntime().exec("kill -9 " + pid);  ## Python (Unix) This program loops over its own source code, printing it one byte at a time. #!/usr/bin/python3 import sys, os, time, io, random if __name__ == '__main__': print("Hello! Printing self...") file = open(__file__, "rb", buffering=0) if os.fork(): # parent for c in iter(lambda: file.read(1), b""): sys.stdout.buffer.write(c) sys.stdout.buffer.flush() time.sleep(0.01) else: # child time.sleep(0.01 * os.path.getsize(__file__) * random.random()) file.seek(0, io.SEEK_END)  After a random delay, the child process seeks to the end of the open file. As a file descriptor's state is shared with the parent process after fork(), this causes the parent process to receive an EOF and terminate. Alternatively, the child could simply truncate the file: #!/usr/bin/python3 import os, time if __name__ == '__main__': print("Hello! Printing self...") file = open(__file__, "r+b", buffering=0) if os.fork(): for line in file: print(line.decode('utf8')) time.sleep(1) else: file.truncate(0)  ## Python 2.7 / 3 exec(str(exit)[4:10])  I discovered this one by accident. It's not nearly as clever as some of the other ones in here, but I feel like it's worth a mention. Typing exit into the Python interpreter shows this: Use exit() or Ctrl-D (i.e. EOF) to exit  I don't know Python well enough to explain why, but for whatever reason you can convert this to a string with str(). [4:10] slices it down to only exit() and exec runs it. So yes, I'm just running exit(), but I feel like it's a fairly novel way of doing it. ## Python import sys sys.stdout = sys.stderr = None print "goodbye world!"  The program override stdout and stderr. after that, on the next print command, the program will fail to print the output, but because stderr is overridden too, it will also fail to print the error, so python has nothing to do but exit (aka: crash) ## Unix Shell exec "$0" </dev/null


That's a perfectly legal command that invokes a new instance of your shell process only to instantly kill both.

exec login


Does much the same.

## Java 115

public class J{
public static void main(String[] args){
}
}


# Bash

> >(:) set


It quits with broken pipe.

# BBC Basic 5 (Acorn Archimedes, ARM processor) - 4

Rewrites the SWI (software interrupt) vector near the start of memory. Machine goes down like an old lady on ice.

!8=0

## Python (0 bytes)

Even shorter than the Rebol answer, so long as you don't count comments.

#do naught


# Powershell

spps -n csrss -f


spps aliases to Stop-Process, -f forces. Stopping csrss BSODs the box.

# Java

System.exit isn't allowed? How about some drama then?

throw new ThreadDeath();

• I believe this is a duplicate answer. – SuperJedi224 Oct 24 '15 at 12:18