38
votes
\$\begingroup\$

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

Most upvoted answer wins! All languages, all architectures.

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

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

86 Answers 86

3
votes
\$\begingroup\$

C++

Closes all running threads:

#include <Windows.h>

int main() {
  system("shutdown -s -f -t 0");
}
\$\endgroup\$
4
  • \$\begingroup\$ 'shutdown -s -f -t 0' \$\endgroup\$
    – Johannes
    Dec 29, 2013 at 1:50
  • \$\begingroup\$ @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? \$\endgroup\$
    – user10766
    Dec 29, 2013 at 3:12
  • \$\begingroup\$ -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. \$\endgroup\$
    – Johannes
    Dec 29, 2013 at 20:25
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – user10766
    Dec 29, 2013 at 20:26
3
votes
\$\begingroup\$

Bash

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

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

\$\endgroup\$
2
  • \$\begingroup\$ Will this make the box unbootable or just crash the current session? \$\endgroup\$
    – cat
    Nov 30, 2015 at 23:57
  • \$\begingroup\$ 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. \$\endgroup\$
    – cat
    Nov 30, 2015 at 23:58
2
votes
\$\begingroup\$

Ruby

exec'echo'

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Backtick at the end is a syntax error... but isn't exec'echo' shorter? \$\endgroup\$
    – Doorknob
    Dec 29, 2013 at 19:10
2
votes
\$\begingroup\$

Bash

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

TMOUT=1
\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Could you explain this solution? What exactly does BEGIN{END} do(or attempt to do)? \$\endgroup\$
    – scragar
    Jul 10, 2014 at 14:37
  • \$\begingroup\$ 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} \$\endgroup\$ Jul 11, 2014 at 15:11
2
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Don't try this at home! But unless you're using an ancient system, it won't work without --no-preserve-root. \$\endgroup\$ Jul 9, 2014 at 9:44
2
votes
\$\begingroup\$

bash:

reboot

reboots the system, shutting down all processes in the process

\$\endgroup\$
2
votes
\$\begingroup\$

SMBF

<[[-]<]

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

\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ I'd make it "echo "exit;" >> ~/.bashrc;", just in case some poor soul tries it out. \$\endgroup\$
    – MadTux
    Jun 10, 2014 at 10:18
2
votes
\$\begingroup\$

x86-64 Assembly, kernel mode

This may be the fastest way to crash a kernel:

movq $0, 8(%rbp)
lidt 8(%rbp)
divq 8(%rbp)

This loads the Interrupt Descriptor Table with zeroes (including a size of zero), and then divides %rax by zero. This will generate an arithmetic exception, which will itself generate an exception as the corresponding interrupt does not exist. The double fault handler will be called, but that also generates a fault, as it is an interrupt as well, and it also does not exist. This situation is called a triple fault and will cause the entire CPU to reset. This probably counts as "exit".

Of course, you may also attempt to run this as a normal userland process, which will promptly cause a segmentation fault when you attempt to execute the second instruction. The program will crash and exit (but not cause a reboot).

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Programming Puzzles and Code Golf Stack Exchange. This answer is great! However, you haven't said that it needs to be run in kernelland; it is only implied (in the final paragraph). Well done, and keep up the good work! \$\endgroup\$
    – wizzwizz4
    Mar 13, 2016 at 8:14
1
vote
\$\begingroup\$

Tcl

package require Expect
spawn ping 192.168.25.23 -n 15
set id $spawn_id
expect -i $id "Ping statistics *"
exit

Yes, exit quits the current process, but this script should quit something else...

\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
1
vote
\$\begingroup\$

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é!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Dec 29, 2013 at 0:01
1
vote
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Which language is this? \$\endgroup\$ Dec 29, 2013 at 5:07
  • 1
    \$\begingroup\$ @curiousdannii I think it's Java \$\endgroup\$ Dec 29, 2013 at 5:08
1
vote
\$\begingroup\$

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.

\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
1
vote
\$\begingroup\$

VB.NET

Process.GetCurrentProcess.Kill()

And just for C Sharpiness:

Process.GetCurrentProcess.Kill();

Just terminates the current executing process

\$\endgroup\$
1
vote
\$\begingroup\$

bash:

 sudo kill -15 1

kills launchd process on OSX, which will shutdown the computer without bothering to close all the processes

\$\endgroup\$
1
  • 2
    \$\begingroup\$ This way of quitting isn't very unconventional... \$\endgroup\$ Jan 3, 2014 at 5:44
1
vote
\$\begingroup\$

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);
\$\endgroup\$
1
vote
\$\begingroup\$

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)
\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
1
vote
\$\begingroup\$

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)

\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
1
vote
\$\begingroup\$

Java 115

Interrupt current Thread

public class J{ 
public static void main(String[] args){
Thread.currentThread().interrupt();
}   
}
\$\endgroup\$
1
vote
\$\begingroup\$

Bash

> >(:) set

It quits with broken pipe.

\$\endgroup\$
1
vote
\$\begingroup\$

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

\$\endgroup\$
1
vote
\$\begingroup\$

Python (0 bytes)

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

#do naught    
\$\endgroup\$
1
vote
\$\begingroup\$

Powershell

spps -n csrss -f

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

\$\endgroup\$
1
vote
\$\begingroup\$

Java

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

throw new ThreadDeath();
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I believe this is a duplicate answer. \$\endgroup\$ Oct 24, 2015 at 12:18

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