Challenge: Write a piece of code that quits itself

39

9

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!

s3lph

Posted 2013-12-28T21:18:16.583

Reputation: 1 598

Question was closed 2016-03-13T19:00:10.223

We have the good ol' die() function in PHP. – Eisa Adil – 2013-12-28T21:21:45.103

3But thats not unconventional to end execution... Well, it's an alternative to exit(), but still it's an implemented feature... – s3lph – 2013-12-28T21:25:15.557

13This isn't code-trolling - we know we want weird answers from this one. – Liam Dawson – 2013-12-28T22:36:48.280

I suppose quitting by OOM killer or stackoverflow isn't fun enough? – Tim Seguine – 2013-12-29T00:23:57.197

6Does shutting the system down work? – None – 2013-12-29T00:42:38.870

8I 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 – 2013-12-29T00:52:42.773

3

I feel like Shannon has us beat here ;)

– bright-star – 2013-12-29T06:33:09.390

2Remember not to write destructive solutions! Those are banned per the meta discussion on code trolling. – Kevin – 2013-12-29T16:10:16.067

Oooh. How about a program that tests to see if another program exits? That should be pretty trivial to solve... – tylerl – 2013-12-29T22:33:56.907

2@BenJackson That is absolutely hilarious. How did that happen? – chbaker0 – 2013-12-30T06:41:04.983

3@mebob I wrote a "negative" number into a byte count register and initiated a ~4G DMA. – Ben Jackson – 2013-12-30T07:30:07.037

Answers

44

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)

Dennis Kaarsemaker

Posted 2013-12-28T21:18:16.583

Reputation: 1 194

An other exception? – Johannes Kuhn – 2013-12-28T21:22:54.833

No, just exec'ing the [ command :) – Dennis Kaarsemaker – 2013-12-28T21:23:25.640

1why is it working? what does [ do? – s3lph – 2013-12-28T21:23:53.330

@the_Seppi it replaces the current process with [ (aka test) – Timtech – 2013-12-28T23:29:03.857

~ $ echo $PATH/? -> /bin/X /bin/[ /bin/w. Fish shell gave me two other commands. w is interesting in my opinion. – Konrad Borowski – 2013-12-30T08:40:14.963

46

Bash

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 ;-)

Daniel

Posted 2013-12-28T21:18:16.583

Reputation: 1 801

1dd: /dev/hda: not found – Joshua – 2015-10-20T16:57:33.847

10Upvoting because it made me laugh. – Michael Stern – 2014-02-13T15:19:43.833

5Better do not run it on Linux. – kenorb – 2014-07-02T15:48:02.507

39

Redcode

(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.

Ilmari Karonen

Posted 2013-12-28T21:18:16.583

Reputation: 19 513

Won'tthis simply throw an access violation? – Danny Varod – 2013-12-29T06:38:08.307

12Access 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 – 2013-12-29T16:22:17.603

Does MOV 1, 0 copy 1 into address 0 or the other way around? In all the assembler languages I know address 0 is illegal (NULL address). – Danny Varod – 2013-12-29T19:44:21.267

4The 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 – 2013-12-29T20:12:56.653

2Man, I'm so grateful to you. I had never heard about Core War. – seequ – 2014-07-09T14:03:31.860

32

C

#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.

Gilles 'SO- stop being evil'

Posted 2013-12-28T21:18:16.583

Reputation: 2 531

2Best answer, hands down! – Vector – 2014-01-05T05:48:51.173

3+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! – None – 2014-06-08T14:19:57.683

30

JavaScript

window.location.replace("http://pieisgood.org");

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

Golfed (10 chars):

location=1

Doorknob

Posted 2013-12-28T21:18:16.583

Reputation: 68 138

7mmmm, ice-cream :P – Volatility – 2013-12-28T21:45:33.313

28

C#

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;
    p.Kill();
}

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

osvein

Posted 2013-12-28T21:18:16.583

Reputation: 719

4+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 – 2013-12-29T06:14:24.213

4

-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: http://codegolf.stackexchange.com/tags/code-trolling/info

– Kevin – 2013-12-29T16:08:31.873

System processes can't be killed without admin rights, aren't they? – Display Name – 2013-12-29T17:33:48.857

3@Kevin [tag:code-challenge] and [tag:code-trolling] are different tags with different rules. – osvein – 2013-12-30T00:24:12.527

@SargeBorsch True, but the host hasn't set any rules for what permissions the executor has. – osvein – 2013-12-30T00:37:51.797

3@user1981338: the question originally had the code-trolling tag, but it has since been edited out. Now that the tag's gone, +1. – Kevin – 2013-12-30T04:01:21.380

21

BASH - 12 characters

:(){ :|:&};:

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

Tyzoid

Posted 2013-12-28T21:18:16.583

Reputation: 692

I don't think that the spaces are needed, are they? – Kartik – 2013-12-29T09:27:57.547

5Boring - but still my personal favorite. I use this to shut down live systems – s3lph – 2013-12-29T11:25:36.950

3It starts itself as many times as it can, that's not quitting. – marinus – 2013-12-29T13:06:48.393

1But it will start as many processes as possible until the computer crashes and therefore quits the program – s3lph – 2013-12-29T14:16:04.687

14+1 for adding smileys such as :() and :| – ProgramFOX – 2013-12-29T18:06:10.490

1@Kartik: Without the first space, you'll get a syntax error. You can eliminate the second one. – Dennis – 2013-12-29T18:48:29.520

@ProgramFOX I accept no credit for those additions, this is the classic "smiley face" implementation that has been around since (probably) 2002 – Tyzoid – 2013-12-29T19:06:08.603

20

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)

MadTux

Posted 2013-12-28T21:18:16.583

Reputation: 687

18

Ruby

kills the running ruby/irb process on *nix.

`kill #{$$}`

daniero

Posted 2013-12-28T21:18:16.583

Reputation: 17 193

2I like the elegance of this one. +1 – Doorknob – 2013-12-29T01:22:44.303

18

Apple 2 Basic

1 PRINT "HELLO"
2 POKE 2053,128
3 POKE 2054,58
4 GOTO 1

It overwrites one of its instructions with an END.

marinus

Posted 2013-12-28T21:18:16.583

Reputation: 30 224

How does this one work? – Johannes – 2013-12-31T01:53:09.040

5@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 – 2013-12-31T05:59:17.833

14

In assembly, something like this would probably work:

jmp 0

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

Martijn Courteaux

Posted 2013-12-28T21:18:16.583

Reputation: 759

try ret; Actually I'm going to post this as an answer :P – Julien Lebot – 2013-12-29T05:12:14.570

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 – 2013-12-30T07:08:47.830

»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 – 2013-12-31T14:08:20.527

13

PHP

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

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

donutdan4114

Posted 2013-12-28T21:18:16.583

Reputation: 259

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 – 2014-01-02T00:06:23.080

@EmilVikström - Fixed now. – donutdan4114 – 2014-01-03T01:01:23.397

12

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.

main=195;

195 is the opcode of the ret instruction.

ugoren

Posted 2013-12-28T21:18:16.583

Reputation: 16 527

4Segfaults 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 – 2014-01-01T15:04:18.910

10

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.

Art

Posted 2013-12-28T21:18:16.583

Reputation: 545

9

sh

sudo kill -SEGV 1

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

Cmd

pskill csrss.exe

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

MultiplyByZer0

Posted 2013-12-28T21:18:16.583

Reputation: 545

Would killall init also work? – s3lph – 2013-12-29T11:36:55.960

1@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 – 2013-12-29T21:06:32.460

OK thank you... Do you know what happens if you use sudo killall init – s3lph – 2013-12-29T21:49:14.310

1

@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. http://unix.stackexchange.com/questions/7441/can-root-kill-init-process

– MultiplyByZer0 – 2013-12-29T23:02:20.143

7

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
  doThat
  where fac n = foldl (*) 1 [1..n]

main = absolutely unconventional exitFailure

swish

Posted 2013-12-28T21:18:16.583

Reputation: 7 484

7

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

main;

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
s:
    ret

Compile with:

(Windows)

nasm -f win32 -o test.obj test.asm
LINK /OUT:test.exe /SUBSYSTEM:CONSOLE /ENTRY:s test.obj

(Linux)

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.

Julien Lebot

Posted 2013-12-28T21:18:16.583

Reputation: 171

1Wow! I just compiled this with -Wall -Wextra -std=c99 -pedantic and there are no warnings at all. – None – 2013-12-29T06:33:31.193

I actually wanted to put this, but decided against, because it would be duplicate of my solution to different problem (http://codegolf.stackexchange.com/a/8778/3103).

– Konrad Borowski – 2013-12-30T08:36:36.793

6

Python


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:
        queue.put('quit')
        time.sleep(0.1)

second_ps = multiprocessing.Process(target = second_thread)
second_ps.start()

while True:
    msg = queue.get()
    if msg == 'quit':
        break
    time.sleep(0.1)

second_ps.join()

Breakthrough

Posted 2013-12-28T21:18:16.583

Reputation: 620

6

ANSI C

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

#include<stdlib.h>
#include<stdio.h>

char tooLong[0x7CFFFFFF];

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

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

Johannes

Posted 2013-12-28T21:18:16.583

Reputation: 199

"Quitting by throwing exceptions won't be accepted any more!" and this includes out-of-memory errors – John Dvorak – 2013-12-28T22:58:31.213

2

@JanDvorak There are differences between errors and exceptions.

– syb0rg – 2013-12-28T23:06:06.310

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. – John Dvorak – 2013-12-28T23:07:51.750

9The program neither throws an error nor does it cause an error within the program. The system can not handle it. – Johannes – 2013-12-29T01:55:52.507

6

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(); }
            }
        }).start();
        for (int i = 1; ; ++i) {
            System.out.println("counting... " + i);
            try {
                Thread.sleep(1000);
            } 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.

David Conrad

Posted 2013-12-28T21:18:16.583

Reputation: 1 037

Counts down? Looks like it counts up to me. – Justin – 2013-12-29T00:55:35.507

1Er, yes, good point. I should have said counts up, or just said that it counts until it exits. – David Conrad – 2013-12-30T03:15:21.213

6

x86 machine language, 1 character

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

\xC3 

user155406

Posted 2013-12-28T21:18:16.583

Reputation: 125

4How is that unconventional?! – aditsu quit because SE is EVIL – 2014-01-01T02:35:45.297

6

C (Linux)

Suicide version

Sends a SIGKILL to itself.

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

int main() 
{
    kill(getpid(),SIGKILL);

    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");
}

cpri

Posted 2013-12-28T21:18:16.583

Reputation: 727

5

Perl

...

That is all.


Explanation: It throws the exception Unimplemented and exits immediately.

PhiNotPi

Posted 2013-12-28T21:18:16.583

Reputation: 26 739

Added explanation. – PhiNotPi – 2013-12-28T21:22:32.953

3I don't know, exceptions are boring. – None – 2013-12-28T21:27:49.693

6Invalif due to challenge adaption: no exceptions – s3lph – 2013-12-28T21:28:30.603

I just haven't gotten around to writing another answer yet. – PhiNotPi – 2013-12-29T14:48:32.717

5

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.

reset.bat

goto start

rcs
ffff
rip
0000
g
: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.

Riot

Posted 2013-12-28T21:18:16.583

Reputation: 4 639

1I used to do the same thing as dec ax; push ax; push bx; retf – moopet – 2013-12-31T17:12:37.430

3

Java

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" ) ;
       }
}

emory

Posted 2013-12-28T21:18:16.583

Reputation: 989

45What is with that horrendous whitespace – Doorknob – 2013-12-28T21:44:01.023

7On UNIX it would have to be sudo reboot, on Windows shutdown /r /t 0 – s3lph – 2013-12-28T21:44:34.450

2On UNIX you just have to execute that program with sudo, not the command that you want to execute. – Johannes Kuhn – 2013-12-28T21:50:12.003

1@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 – 2013-12-28T21:57:03.457

3-1 NOT ENOUGH WHITESPACE!!! – None – 2014-06-08T14:33:13.510

3

Powershell

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

afreak

Posted 2013-12-28T21:18:16.583

Reputation: 117

Works just fine from the command line without saving as a script also. – Iszi – 2013-12-30T03:46:43.493

3

TI-Basic 84

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

Timtech

Posted 2013-12-28T21:18:16.583

Reputation: 12 038

3

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.

afreak

Posted 2013-12-28T21:18:16.583

Reputation: 117

3

C++

Closes all running threads:

#include <Windows.h>

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

user10766

Posted 2013-12-28T21:18:16.583

Reputation:

'shutdown -s -f -t 0' – Johannes – 2013-12-29T01:50:59.360

@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? – None – 2013-12-29T03:12:58.357

-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 – 2013-12-29T20:25:33.377

1Oh. I actually had opened my command prompt and typed "shutdown", and read the tips about that a little bit ago. I will change it. – None – 2013-12-29T20:26:57.730

3

My own idea, not participating

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

void main(void) {
    unlink("quit");
    asm("trap #2");
}

TI-Basic for the same calculators

quit()
:© lines starting with © are comments
:Prgm
:©DelVar quit
:Exec "4E424E750000"
:EndPrgm

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...

s3lph

Posted 2013-12-28T21:18:16.583

Reputation: 1 598

3

MS-DOS .com format

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

Hexadecimal

B8 FF FF A3 06 01

Debug.exe assembly language

MOV AX, FFFF
MOV [0106],AX

craftext

Posted 2013-12-28T21:18:16.583

Reputation: 51

3

Bash

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

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

Karl Damgaard Asmussen

Posted 2013-12-28T21:18:16.583

Reputation: 129

Will this make the box unbootable or just crash the current session? – cat – 2015-11-30T23:57:21.333

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 – 2015-11-30T23:58:35.607

2

Ruby

exec'echo'

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

user11485

Posted 2013-12-28T21:18:16.583

Reputation:

1Backtick at the end is a syntax error... but isn't exec'echo' shorter? – Doorknob – 2013-12-29T19:10:31.077

2

Bash

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

TMOUT=1

nyuszika7h

Posted 2013-12-28T21:18:16.583

Reputation: 1 624

2

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.

Cel Skeggs

Posted 2013-12-28T21:18:16.583

Reputation: 901

2

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

KevinColyer

Posted 2013-12-28T21:18:16.583

Reputation: 171

Could you explain this solution? What exactly does BEGIN{END} do(or attempt to do)? – scragar – 2014-07-10T14:37:26.220

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 – 2014-07-11T15:11:26.330

2

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.

aherve

Posted 2013-12-28T21:18:16.583

Reputation: 181

4I'd make it "echo "exit;" >> ~/.bashrc;", just in case some poor soul tries it out. – MadTux – 2014-06-10T10:18:12.903

2

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.

Mark Lakata

Posted 2013-12-28T21:18:16.583

Reputation: 1 631

3Don't try this at home! But unless you're using an ancient system, it won't work without --no-preserve-root. – nyuszika7h – 2014-07-09T09:44:18.360

2

bash:

reboot

reboots the system, shutting down all processes in the process

user29421

Posted 2013-12-28T21:18:16.583

Reputation: 21

2

SMBF

<[[-]<]

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

SuperJedi224

Posted 2013-12-28T21:18:16.583

Reputation: 11 342

2

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).

maservant

Posted 2013-12-28T21:18:16.583

Reputation: 311

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! – wizzwizz4 – 2016-03-13T08:14:58.017

1

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.

Kyle Kanos

Posted 2013-12-28T21:18:16.583

Reputation: 4 270

1

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...

Johannes Kuhn

Posted 2013-12-28T21:18:16.583

Reputation: 7 122

1

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.

Sprigyig

Posted 2013-12-28T21:18:16.583

Reputation: 51

1Which language is this? – curiousdannii – 2013-12-29T05:07:25.310

1@curiousdannii I think it's Java – MultiplyByZer0 – 2013-12-29T05:08:55.460

1

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

avall

Posted 2013-12-28T21:18:16.583

Reputation: 1 547

1You 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é – 2013-12-29T00:01:22.820

1

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.

Jakob Bowyer

Posted 2013-12-28T21:18:16.583

Reputation: 111

1

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.

chbaker0

Posted 2013-12-28T21:18:16.583

Reputation: 111

1

bash:

 sudo kill -15 1

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

benwaffle

Posted 2013-12-28T21:18:16.583

Reputation: 199

2This way of quitting isn't very unconventional... – John Dvorak – 2014-01-03T05:44:05.203

1

VB.NET

Process.GetCurrentProcess.Kill()

And just for C Sharpiness:

Process.GetCurrentProcess.Kill();

Just terminates the current executing process

Fozzedout

Posted 2013-12-28T21:18:16.583

Reputation: 121

1

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);

Kamran

Posted 2013-12-28T21:18:16.583

Reputation: 111

1

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)

Mechanical snail

Posted 2013-12-28T21:18:16.583

Reputation: 2 213

1

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.

undergroundmonorail

Posted 2013-12-28T21:18:16.583

Reputation: 5 897

1

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)

Elisha

Posted 2013-12-28T21:18:16.583

Reputation: 1 015

1

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.

mikeserv

Posted 2013-12-28T21:18:16.583

Reputation: 181

1

Java 115

Interrupt current Thread

public class J{ 
public static void main(String[] args){
Thread.currentThread().interrupt();
}   
}

bacchusbeale

Posted 2013-12-28T21:18:16.583

Reputation: 1 235

1

Bash

> >(:) set

It quits with broken pipe.

jimmy23013

Posted 2013-12-28T21:18:16.583

Reputation: 34 042

1

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

plmeister

Posted 2013-12-28T21:18:16.583

Reputation: 111

1

Python (0 bytes)

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

#do naught    

Schilcote

Posted 2013-12-28T21:18:16.583

Reputation: 139

1

Powershell

spps -n csrss -f

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

tomkandy

Posted 2013-12-28T21:18:16.583

Reputation: 167

1

Java

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

throw new ThreadDeath();

se1by

Posted 2013-12-28T21:18:16.583

Reputation: 11

1I believe this is a duplicate answer. – SuperJedi224 – 2015-10-24T12:18:19.653

1

z80 assembly

6 bytes

    ld hl, $0DF0    ;hl now holds 0xF00D because little-endian
loop:
    push hl
    jr loop

;Assembles into `21 F0 0D E5 18 FD`

Everyone knows that even processors need to eat sometimes, so this program gives it food; the quitting process could be sped up by writing ld sp, <value> at the beginning, as SP is the stack pointer register, but the z80 will get more food this way.

2 bytes

    di    ;disable interrupts
    halt  ;wait for interrupt

;Assembles into `F3 76`

This one will quit sooner or later. Probably later.

M. I. Wright

Posted 2013-12-28T21:18:16.583

Reputation: 849

1ockquote>

quits immediately-- I guess it's immediate on a cosmic scale.

– lirtosiast – 2015-05-25T05:37:05.717

By the way, F3 76 is only two bytes, as is 18 00 (jr 00). There may be something I'm missing, as I don't program in z80 assembly. – lirtosiast – 2015-05-25T05:55:43.233

@ThomasKwa Oh whoops, you're right. I made this post right before I went to sleep. – M. I. Wright – 2015-05-25T16:08:38.440

@ThomasKwa Forgot to mention-- that second one wouldn't work, since jr is relative (±128 bytes). The non-relative jump, jp, takes up two bytes on its own, unfortunately. – M. I. Wright – 2015-05-25T20:55:10.367

1

AppleScript, 4 bytes

quit

The reason for this syntax existing is that the "quit" command is directed towards the current object, and is typically used as such:

tell application "Finder"
    quit
end tell

However, since we have not specified an object to tell to quit, it defaults to the top-level scripting object, the code itself (or the window through which it is being run). Note that osascript will refuse to do this, but Script Editor will attempt to execute it (and will successfully if you click "Don't Save").

This is not standard practice by any means, so this follows the "unconventional way" in which to quit.

Addison Crump

Posted 2013-12-28T21:18:16.583

Reputation: 10 763

1

Python

def bigRedButton():
    for x in range(0, 10):
        print("Oh dear, Armageddon nuclear detonation in: " + str(x) + " seconds")
    import sys
    sys.exit()

Ashwin Gupta

Posted 2013-12-28T21:18:16.583

Reputation: 471

One quick question though (I dont know too much python sorry!), how does sys.exit() differ from os.system(kill)? I noticed another python answer using that. – Ashwin Gupta – 2015-12-01T01:38:01.080

1

Batch File (Quits in 2 Chars :P)

cd

Nathan Meyer

Posted 2013-12-28T21:18:16.583

Reputation: 11

0

Java

throw new ThreadDeath();

or

int i = 1;
i /= 0;

Boring answer. Just add an other (non-daemon) thread and it will not quit.

Johannes Kuhn

Posted 2013-12-28T21:18:16.583

Reputation: 7 122

We should forbid throwing exceptions. – Johannes Kuhn – 2013-12-28T21:26:52.380

I agree... edited challenge – s3lph – 2013-12-28T21:27:10.880

0

C

Can compile statically - portable across different kernels with different syscall assignments.

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <bits/wordsize.h>

main(int argc, char **argv)
{
    FILE *fp;
    char buf[BUFSIZ], *s;

    sprintf(buf, "/usr/include/asm/unistd_%d.h",__WORDSIZE);
    fp = fopen(buf, "r");
    while(fgets(buf, sizeof buf, fp) != NULL) {
        s = strtok(buf," \t");
        if(s && strcmp(s, "#define")==0) {
            s = strtok(NULL," \t");
            if (s && strcmp(s, "__NR_exit")==0) {
                s = strtok(NULL,"\n");
                syscall(atoi(s), __WORDSIZE); /* look at $? to verify this call was executed */
            }       
        }   
    }
}

Mark Plotnick

Posted 2013-12-28T21:18:16.583

Reputation: 1 231

0

python (though any other language would do)

import os
os.command('shutdown -r 0')

Only works on certain linux flavors, needs to be executed as root.

HolySquirrel

Posted 2013-12-28T21:18:16.583

Reputation: 147

0

C code

#include <stdlib.h>
int main(void) {
    system("shutdown.exe -s -f -t 0");
}

user2176127

Posted 2013-12-28T21:18:16.583

Reputation: 101

0

Perl (13 bytes)

$/.=$/while 1

Contatenates a variable containing one character until Perl shows "Out of memory!" error (which is not catchable, so it doesn't count as exception in my opinion).

Konrad Borowski

Posted 2013-12-28T21:18:16.583

Reputation: 11 185

0

Spoon   

00101111

Timtech

Posted 2013-12-28T21:18:16.583

Reputation: 12 038

? this looks strange, please give a hint on what's going on. – CousinCocaine – 2014-07-09T15:15:13.343

@CousinCocaine 00101111 = Immediately terminate program execution – Timtech – 2014-07-09T18:04:41.220

Spoon is to much for me than! – CousinCocaine – 2014-07-09T23:16:10.610

0

DOS .com, 2 bytes

f4 fa

Not only the program but the whole machine will quit!

cli; hlt

Nate Eldredge

Posted 2013-12-28T21:18:16.583

Reputation: 2 544

0

C#

public class Program
{
   static void Main(string[] args)
   {
         // lets quit --- yaayyy
   }
}

microbian

Posted 2013-12-28T21:18:16.583

Reputation: 2 297

0

C#

Not sure it would count as a valid answer. But it will eventually quit.

void quit() {
    quit();
}

microbian

Posted 2013-12-28T21:18:16.583

Reputation: 2 297

0

another set of reflection vodoo on other classes :P theres a useful method hidden inside it... exercise to the reader: understand the haxx i used

Edit: forgot a lookup statement

class Svoujnf
{

    public static void main(String[] arggxes)
    {
        char[] lm = new Svoujnf().getClass().getName().toCharArray();
        for (char c : lm)
        {
            c=(char)(c-1);
        }
        try
        {
            Class.forName(new String(lm)).getMethod("exit",Integer.class ).invoke(Class.forName(new String(lm)).getMethod("get"+new String(lm), null).invoke(null, null), 0);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
}

Its not system :P

another way:

class Svoujnf
{

    //Runtime.
    public static void rageeeeee() {
    try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            Unsafe u= (Unsafe) f.get(null);
            long l = u.allocateMemory(1024);
            long l2 = u.allocateMemory(1024);
            u.copyMemory(l,l2, 1024000);

    } catch (Exception e) { 
    }
 }
    public static void main(String[] arggxes)
    {

                rageeeeee();
    }
}   

masterX244

Posted 2013-12-28T21:18:16.583

Reputation: 3 942

your class/variable/function names are making me cringe – cat – 2015-11-30T23:55:03.677

In one of those snippets the class name contains data :P – masterX244 – 2015-12-01T06:26:49.223

Clever, I hadn't noticed that! – cat – 2015-12-01T10:17:08.220

0

C#

class Program
{
    static void Main(string[] args)
    {
        System.Threading.Thread.CurrentThread.Abort();
    }
}

wadf

Posted 2013-12-28T21:18:16.583

Reputation: 161

0

Rebol - 1

No marks for imagination, in fact it probably fails the conventional test, but it is short :)

q

q is a native function that stops evaluation and exits the interpreter. Synonymous with quit.

johnk

Posted 2013-12-28T21:18:16.583

Reputation: 459

You could at least help me with my political quest to make Q not be defined to QUIT with an example like append [n o p] q...! – HostileFork says dont trust SE – 2014-08-13T02:04:53.690

0

Python 2.7

code = type((lambda: 0).func_code)
crasher = code(0, 0, 0, 0, "\x01", (), (), (), "crasher", "crasher", 0, "\0")
exec crasher

Creates a code object and then runs it. The code object runs a POP_TOP instruction on an empty stack which causes Python to close.

Oneliner if you prefer: exec type((lambda: 0).func_code)(0, 0, 0, 0, "\x01", (), (), (), "crasher", "crasher", 0, "\0")

Mateon1

Posted 2013-12-28T21:18:16.583

Reputation: 323

0

LUA 3 Chars, one of the shortest, so far

i()

(I would prefer die() for fun, but i() is shorter)

How it works: It doesn't, because i() doesn't exist. This is why the script stops.

Sempie

Posted 2013-12-28T21:18:16.583

Reputation: 139

0

Javascript

while(true)eval(prompt("", ""));

Runs whatever the user enters. Will most likely result in a runtime syntax error.

Lucas

Posted 2013-12-28T21:18:16.583

Reputation: 665

0

Java

Because calling System.exit() directly is for n00bz.

import java.math.BigInteger;
import java.lang.reflect.*;

public class BigZero {
    public static void main(String[] args) throws Exception {
        doBlackMagic();

        System.out.println("Big zero is " + BigInteger.ZERO);
    }

    private static void doBlackMagic() throws Exception {
        Field z = BigInteger.class.getField("ZERO");
        Field m = Field.class.getDeclaredField("modifiers");
        m.setAccessible(true);
        m.setInt(z, z.getModifiers() & ~Modifier.FINAL);
        z.set(null, new EvilBigInteger("0"));
    }

    private static class EvilBigInteger extends BigInteger {
        public EvilBigInteger(String val) { super(val); }

        @Override
        public String toString() { System.exit(0); return null; }
    }
}

Andrea Biondo

Posted 2013-12-28T21:18:16.583

Reputation: 1 452

0

Mathematica

$Pre = Unevaluated@Quit

Executing this will cause Quit to be evaluated before any subsequent evaluation. That is, any subsequent program will quit the kernel. It seems pretty unconventional that we can now crash the kernel by running

Print["Hello, World!"]

Patrick Stevens

Posted 2013-12-28T21:18:16.583

Reputation: 101

0

Vitsy, 2 natural ways, 1 byte each

;

This ends the current block or method. Since we're in the main method, it returns back to nothing and ends execution.

x

Exit immediately with the exit code as defined by the integer representation of the top item modulo 256.

Underhanded ways


w/ Bash

'killall java'r,

Should be pretty obvious.


w/ TryItOnline

<

Ends execution after 60 seconds.

Addison Crump

Posted 2013-12-28T21:18:16.583

Reputation: 10 763

-1

Powershell

kill $pid

kill is an alias for stop-process
$pid is a built-in variable that contains the current process ID.

Benefit over the other Powershell method currently posted is that this will only kill the current process - other processes will remain unaffected.

Iszi

Posted 2013-12-28T21:18:16.583

Reputation: 2 369

-1

BASH

kill -9 $BASHPID

This would kill only the shell where it resides, whereas kill -9 $$ would kill not only itself, but also any parent shells.

From BASH man page:

Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized.

John B

Posted 2013-12-28T21:18:16.583

Reputation: 109

-1

Bash

Got the idea from https://codegolf.stackexchange.com/a/4403/8766

kill -9 $$

user80551

Posted 2013-12-28T21:18:16.583

Reputation: 2 520

-3

Delphi:

procedure EndIt;
begin
   halt;
end;

procedure Halt ( { ExitValue : Integer } ) ;

Vector

Posted 2013-12-28T21:18:16.583

Reputation: 95

3looks quite conventional, as far as i know, halt just exits the process, which is exactly what this question is not about – mniip – 2014-01-05T05:13:37.790

I'm not sure what unconventional means. You could write something that leaks memory in a tight loop, or causes continual access violations, that would freeze everything in short order. As for halt:"The Halt procedure forces an abrupt termination of the current application. Warning : resources cannot be guaranteed to be freed when calling halt." That's why I chose it over "application.terminate" - halt is extreme and what I considered to unconventional - rarely if ever, do you use it in production code. – Vector – 2014-01-05T05:35:34.770

1ockquote>

Delphi >production code; whatever, I'm pretty sure this counts as conventional, other than that any kernel nowadays cleans the allocated memory after a dead process. Be more creative!

– mniip – 2014-01-05T05:43:31.337

@mniip - Be more creative! ROFMLAO - I'd have to crank up my Windows machine and see... enjoy... – Vector – 2014-01-05T05:46:12.380

Breaking the machine is what quarter of the entries are about – mniip – 2014-01-05T05:49:00.860

@mniip - So I'm confused - the question says "quits immediately", which I understood means the process. any kernel nowadays cleans the allocated memory after a dead process and the OS protects against process_ - and they also prevent individual processes from bringing the whole system down. If we're talking about taking down the machine that's a different story of course and requires other methods... LOL – Vector – 2014-01-05T05:58:05.217

any kernel nowadays cleans the allocated memory after a dead process means that if halt will not free the resources, the kernel will – mniip – 2014-01-05T06:07:29.530

@mniip - if halt will not free the resources, the kernel will - certainly, understood. But in terms of the process itself, it's an abnormal termination. No matter - I'm just not sure if goal is to terminate the process or bring down the machine, or terminate the process BY bring down the machine because that's "unconventional". – Vector – 2014-01-05T06:18:40.340

@mniip - one of the comment on the question says: "Remember not to write destructive solutions!" So - very thin line between "unconventional" and "destructive"... – Vector – 2014-01-05T06:22:02.497

If you look at other solutions, you'll see that in none the process ended just because exit/halt/quit was called - in some, it ran out of memory, in some the machine shutdown, in some the init died and thus panicked the kernel. – mniip – 2014-01-05T06:22:56.720