text:
Shortest code to throw SIGILL
Background
We already have a challenge about throwing SIGSEGV, so why not a challenge about throwing SIGILL?
What is SIGILL?
SIGILL is the signal for an illegal instruction at the processor, which happens very rarely. The default action after receiving SIGILL is terminating the program and writing a core dump. The signal ID of SIGILL is 4. You encounter SIGILL very rarely, and I have absolutely no idea how to generate it in your code except via sudo kill -s 4 <pid>.
Rules
You will have root in your programs, but if you don't want to for any reasons,  you may also use a normal user. I'm on a Linux computer with German locale and I do not know the English text which is displayed after catching SIGILL, but I think it's something like 'Illegal instruction'. The shortest program which throws SIGILL wins.

You might want to clarify whether the instruction has to be generated by the kernel or not. In particular, do you want to allow the program just generating it directly using the libc call raise(SIGILL)?

It really does say Illegal instruction (core dumped).

@ais523 Everything is allowed.

For any hardware that can raise SIGILL, the answer will be the same as the instruction length. Just put an illegal instruction somewhere and try to execute it. The only interesting thing will be the convoluted toolchain involved.

@CarstenS Uh. Yes, of course I mean that.

Now please explain me why I have even more votes then the SIGSEGV question? XD

*people posting old programs they had that didn't work*

Sometimes I look for the brainfuck entry, just to marvel at how it lives up to its name.   Honestly I was expecting someone would have come up with a negative-length brainfuck submission, just cos.

@Criggie where is the brainfuck entry? I don’t see it.

@BenjaminWang there isn't one here, yet.  That language really does deserve it's name.

PDP-11 Assembler (UNIX Sixth Edition), 1 byte
9

Instruction 9 is not a valid instruction on the PDP-11 (in octal, it would be 000011, which does not appear on the list of instructions (PDF)). The PDP-11 assembler that ships with UNIX Sixth Edition apparently echoes everything it doesn't understand into the file directly; in this case, 9 is a number, so it generates a literal instruction 9. It also has the odd property (unusual in assembly languages nowadays) that files start running from the start, so we don't need any declarations to make the program work.
You can test out the program using this emulator, although you'll have to fight with it somewhat to input the program.
Here's how things end up once you've figured out how to use the filesystem, the editor, the terminal, and similar things that you thought you already knew how to use:
% a.out
Illegal instruction -- Core dumped

I've confirmed with the documentation that this is a genuine SIGILL signal (and it even had the same signal number, 4, all the way back then!)

It had the same signal number because POSIX and UNIX and the SUS are closely related :)

Almost all of the signal numbers in V6 still have the same meanings today; the mnemonics have actually been less stable than the numbers.  Compare http://minnie.tuhs.org/cgi-bin/utree.pl?file=V6/usr/sys/param.h with https://github.com/freebsd/freebsd/blob/master/sys/sys/signal.h — identical semantics for 1 through 13, but  only 1, 2, and 13 have exactly the same names.  (SIGALRM/14 and SIGTERM/15 were only added in V7.)  (The System V lineage has a couple of changes, notably moving SIGBUS from 10 to 7 (replacing the useless SIGEMT) and SIGSYS above 15, to make room for SIGUSR1 and SIGUSR2.)

@cat POSIX and SUS don't actually specify the values of signals - they do specify the meaning of some numbers when passed as arguments to the kill command, but SIGILL is not included.

@Random832: For the record: this is where POSIX documents the required name->number mappings for the kill command.  Wikipedia copied that into a table at the end of this section.  I'm not sure if anything prevents the kill shell command from remapping the numbers itself to make kill -9 work even if SIGKILL is actually a different number in the C API, but that would be really silly (like Deathstation 9000 kind of behaviour).

I'm not convinced that a.out has one byte in it.  Therefore this is not a compete assembler program, just one line of an assembler program that achieves the result.  The byte count of your whole program is the byte count of a.out.

a.out has multiple bytes in it, indeed (the 9 instruction compiles to two bytes, and the assembler also adds a header and footer to make the program executable). That's why I wrote the program in assembly language, not in machine code. The assembly language program has only one byte in, and compiles to a program with more bytes in; this is a [tag:code-golf] problem (minimize the size of the source), not a sizecoding problem (minimize the size of the executable), so it's the 1-byte size of the source that matters.

Very clever abuse of an old but awesome system.

C (x86_64, tcc), 7 bytes
main=6;

Inspired by this answer.
Try it online!
How it works
The generated assembly looks like this.
    .globl  main
main:
    .long 6

Note that TCC doesn't place the defined "function" in a data segment.
After compilation, _start will point to main as usual. When the resulting program is executed, it expects code in main and finds the little-endian(!) 32-bit integer 6, which is encoded as 0x06 0x00 0x00 0x00. The first byte – 0x06 – is an invalid opcode, so the program terminates with SIGILL.

C (x86_64, gcc), 13 bytes
const main=6;

Try it online!
How it works
Without the const modifier, the generated assembly looks like this.
    .globl  main
    .data
main:
    .long   6
    .section    .note.GNU-stack,"",@progbits

GCC's linker treats the last line as a hint that the generated object does not require an executable stack. Since main is explicitly placed in a data section, the opcode it contains isn't executable, so the program terminates will SIGSEGV (segmentation fault).
Removing either the second or the last line will make the generated executable work as intended. The last line could be ignored with the compiler flag -zexecstack (Try it online!), but this costs 12 bytes.
A shorter alternative is to declare main with the const modifier, resulting in the following assembly.
        .globl  main
        .section    .rodata
main:
        .long   6
        .section    .note.GNU-stack,"",@progbits

This works without any compiler flags. Note that main=6; would write the defined "function" in data, but the const modifier makes GCC write it in rodata instead, which (at least on my platform) is allowed to contain code.

Love the complete avoidance of even using a function :) How does this work in C terms, though? Does the compiler see that main is a 6 and try to call it (which I guess would make it give up and try the instruction)?

@JackDobson it's undefined behavior, so it doesn't work in terms of C; you're at the compiler's mercy. Clang even has a warning for this for some reason: "variable named 'main' with external linkage has undefined behavior".

GCC will complain about main not being a function but only if you turn on the warnings (either -Wall or -pedantic will do it).

I think it's pretty standard for executables for Unix-like systems to have text/data/bss segments.  The linker places the .rodata section inside the text segment of the executable, and I expect this will be the case on pretty much any platform.  (The kernel's program-loader only cares about segments, not sections).

Also note that 06 is only an invalid instruction in x86-64.  In 32-bit mode, it's PUSH ES, so this answer only works with compilers that default to -m64.  See http://ref.x86asm.net/coder.html#x06.  The only byte sequence that's guaranteed to decode as an illegal instruction on all future x86 CPUs is the 2 byte UD2: 0F 0B.  Anything else could be some future prefix or instruction-encoding.  Still, upvoted for a cool way to get a C compiler to stick a main label on some bytes!

Huh, that's weird that -z execstack also controls the .data section.  I checked with x86-64 gcc7.1.1 on Arch Linux, and you're right that that @progbits directive makes the data section non-executable, and that -z execstack overrides it, and that the default (with no directive and no option) is an executable .data section.  I guess execstack is more like executability for non-text segments in general.

Swift, 5 bytes
[][0]

Access index 0 of an empty array.  This calls fatalError(), which prints an error message and crashes with a SIGILL.  You can try it here.

This is one of the trickier ones ;)

...why on earth does it crash with a SIGILL? Who thought that was an appropriate signal? Bloody hipsters :D

they don't "choose" that signal, it's probably just that the language is stupid enough to have this possibly cause a SIGILL.

@Asu No; fatalError() intentionally crashes by running ud2.  Why they chose to do that I do not know, but maybe they thought the error message "Illegal instruction" made sense because the program did something illegal.

Brilliant.  I would bet this is also the shortest Swift code to cause a crash.

@JAL Yeah; I can't think of anything shorter.  I tried nil!, but the compiler couldn't infer the result type.  (Also, hi JAL!)

@NobodyNada then, wow, that really doesn't make sense, heh.

@Muzer @Asu The reason that fatalError() causes a SIGILL is because it's meant to be the equivalent of Clang & GCC's __builtin_trap() intrinsic which also executes an illegal instruction on most platforms.

GNU C, 25 bytes
main(){__builtin_trap();}

GNU C (a specific dialect of C with extensions) contains an instruction to crash the program intentionally. The exact implementation varies from version to version, but often the developers make an attempt to implement the crash as cheaply as possible, which normally involves the use of an illegal instruction.
The specific version I used to test is gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0; however, this program causes a SIGILL on a fairly wide range of platfoms, and thus is fairly portable. Additionally, it does it via actually executing an illegal instruction. Here's the assembly code that the above compiles into with default optimization settings:
main:
    pushq %rbp
    movq %rsp, %rbp
    ud2

ud2 is an instruction that Intel guarantees will always remain undefined.

−6: main(){asm("ud2");}

Also, I don't know how we count bytes for raw assembly, but 00 00 0f 0b is the machine language for ud2…

@wchargin: that's an x86 + GNU C answer.  This one is portable to all GNU systems.  Also note that UD2 is only 2 bytes.  IDK where you got those 00 bytes; they're not part of the machine code for UD2.  BTW, as I commented on Dennis's answer, there are one-byte illegal instructions in x86-64 for now, but they're not guaranteed to stay that way.

@wchargin: We count bytes for machine-code functions / programs like you'd expect.  See some of my answers, like Adler32 in 32 bytes of x86-64 machine code, or GCD in 8 bytes of x86-32 machine code.

@PeterCordes why would 00 00 be illegal in x86-64? It's still, as it was in x86, mere add [eax],al, which is perfectly legal.

@Ruslan: They aren't; 00 00 decodes the same in x86-64 (as add [rax], al).  00 00 0f 0b would usually SIGSEGV before SIGILL, unless you happened to have a writeable pointer in rax.

@PeterCordes ah, I've misread your comment. You didn't actually claim that 00 is a one-byte illegal instruction as I had read it.

C (x86_64), 11, 30, 34, or 34+15 = 49 bytes
main[]="/";

c=6;main(){((void(*)())&c)();}

main(){int c=6;((void(*)())&c)();}

I've submitted a couple of solutions that use library functions to throw SIGILL via various means, but arguably that's cheating, in that the library function solves the problem. Here's a range of solutions that use no library functions, and make varying assumptions about where the operating system is willing to let you execute non-executable code. (The constants here are chosen for x86_64, but you could change them to get working solutions for most other processors that have illegal instructions.)
06 is the lowest-numbered byte of machine code that does not correspond to a defined instruction on an x86_64 processor. So all we have to do is execute it. (Alternatively, 2F is also undefined, and corresponds to a single printable ASCII character.) Neither of these are guaranteed to always be undefined, but they aren't defined as of today.
The first program here executes 2F from the read-only data segment. Most linkers aren't capable of producing a working jump from .text to .rodata (or their OS's equivalent) as it's not something that would ever be useful in a correctly segmented program; I haven't found an operating system on which this works yet. You'd also have to allow for the fact that many compilers want the string in question to be a wide string, which would require an additional L; I'm assuming that any operating system that this works on has a fairly outdated view of things, and thus is building for a pre-C94 standard by default. It's possible that there's nowhere this program works, but it's also possible that there's somewhere this program works, and thus I'm listing it in this collection of more-dubious-to-less-dubious potential answers. (After I posted this answer, Dennis also mentioned the possibility main[]={6} in chat, which is the same length, and which doesn't run into problems with character width, and even hinted at the potential for main=6; I can't reasonably claim these answers as mine, as I didn't think of them myself.)
The second program here executes 06 from the read-write data segment. On most operating systems this will cause a segmentation fault, because writable data segments are considered to be a bad design flaw that makes exploits likely. This hasn't always been the case, though, so it probably works on a sufficiently old version of Linux, but I can't easily test it.
The third program executes 06 from the stack. Again, this causes a segmentation fault nowadays, because the stack is normally classified as nonwritable for security reasons. The linker documentation I've seen heavily implies that it used to be legal to execute from the stack (unlike the preceding two cases, doing so is occasionally useful), so although I can't test it, I'm pretty sure there's some version of Linux (and probably other operating systems) on which this works.
Finally, if you give -Wl,-z,execstack (15 byte penalty) to gcc (if using GNU ld as part of the backend), it will explicitly turn off executable stack protection, allowing the third program to work and give an illegal operation signal as expected. I have tested and verified this 49-byte version to work. (Dennis mentions in chat that this option apparently works with main=6, which would give a score of 6+15. I'm pretty surprised that this works, given that the 6 blatantly isn't on the stack; the link option apparently does more than its name suggests.)

On x86-64/linux with gcc6 in its default (lenient) mode, const main=6; works, as do several variations. This linker (which I suspect is also your linker) is capable of generating a jump from .text to .rodata; the problem you were having is that, without const, you're jumping into the writable data segment (.data), which is not executable on modern hardware.  It would have worked on older x86, where the memory protection hardware could not mark pages as readable-but-not-executable.

Note that even in C89, main is required to be a function (§5.1.2.2.1) -- I don't know why gcc considers declaring main as a data object to only deserve a warning, and only with -pedantic on the command line. Someone back in the early 1990s perhaps thought that nobody would do that by accident, but it's not like it's a useful thing to do on purpose except for this sort of game.

... Rereading again, it seems you expected main[]="/" to jump to the read-only data segment, because string literals go in rodata. You've been caught out by the difference between char *foo = "..." and char foo[] = "...". char *foo = "..." is syntactic sugar for const char __inaccessible1[] = "..."; char *foo = (char *)&__inaccessible1[0];, so the string literal does go in rodata, and foo is a separate, writable global variable that points to it.  With char foo[] = "...", however, the entire array goes in the writable data segment.

Bash on Raspbian on QEMU, 4 (1?) bytes
Not my work.  I merely report the work of another.  I'm not even in a position to test the claim.  Since a crucial part of this challenge seems to be finding an environment where this signal will be raised and caught, I'm not including the size of QEMU, Raspbian, or bash.
On Feb 27, 2013 8:49 pm, user emlhalac reported "Getting 'illegal instruction' when trying to chroot" on the Raspberry Pi fora.
ping

producing
qemu: uncaught target signal 4 (Illegal instruction) - core dumped
Illegal instruction (core dumped)

I imagine much shorter commands will produce this output, for instance, tr.
EDIT:  Based on @fluffy's comment, reduced the conjectured lower bound on input length to "1?".

I'd think the [ command would win. :)

GNU as (x86_64), 3 bytes
ud2

$ xxd sigill.S
00000000: 7564 32                                  ud2

$ as --64 sigill.S -o sigill.o ; ld -S sigill.o -o sigill
sigill.S: Assembler messages:
sigill.S: Warning: end of file not at end of a line; newline inserted
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400078

$ ./sigill
Illegal instruction

$ objdump -d sigill
sigill:     file format elf64-x86-64

Disassembly of section .text:

0000000000400078 <__bss_start-0x200002>:>
  400078:       0f 0b                   ud2

There must be a way to express that in a two-byte "source"...

Oh, clever. I was wondering if there was a way to build this which would put the entry point at the start of the file (with no declarations) and which wouldn't incur penalties for an unusual build system configuration. I couldn't find one, but it looks like you did.

@ais523: yeah, my usual NASM / YASM build-script (asm-link) for single-file toy programs would build an executable from this source the same way, since ld defaults the entry point to the start of the text segment or something like that.  I just didn't think of going for asm source size on this one :P

x86 MS-DOS COM file, 2 bytes
EDIT: As pointed out in the comments, DOS itself will not trap the CPU exception and will simply hang (not just the app, the entire OS). Running on a 32-bit NT-based OS such as Windows XP will, indeed, trigger an illegal instruction signal.
0F 0B

From the documentation:

Generates an invalid opcode. This instruction is provided for software testing to explicitly generate an invalid opcode.

Which is pretty self-explanatory. Save as a .com file, and run in any DOS emulator DOS emulators will just crash. Run on Windows XP, Vista, or 7 32-bit.

Does it really generate anything like exception or signal? One emulator I have access to just hangs; which one did you use?

It technically does cause the processor to generate an illegal instruction exception. However, DOS has very limited memory protection and exception handling capabilities, and I wouldn't be surprised if it just lead to undefined behavior / OS crash. The OP didn't say the kernel had to catch the error and print "Illegal Instruction" to the console.

I thought of this solution, but I don't believe it's valid. The question requires an illegal instruction signal, not just an illegal instruction processor trap, so the aim was to find an operating system which would actually generate a signal in response to the #UD trap. (Also, I decided to actually test it, and it appeared to throw my DOS emulator into an infinite loop.)

I tested this on actual MS-DOS on an AMD K6-II.  Running it just hangs the system, both with and without EMM386 running.  (EMM386 traps some errors and halts the system with a message, so it was worth testing to see if it made a difference.)

Awesome, some people still have actual MS-DOS systems! I'm stuck with an emulator :( . I do kind of agree with ais523, this is not actually a signal, it just triggers an interrupt and passes control to the operating system, which emits the actual signal. If the OS doesn't have a way to handle this situation, it will most likely just crash (which may not count as a solution).

Try it on Windows 98 or similar?

Yes, DOS-based windows should be able to really catch the trap and at least crash the app.

@Asu I can confirm that this works on XP 32-bit, and will probably work on all other 32-bit Windows systems. I agree that this isn't a solution on DOS itself, as it just crashes.

OK, now you've found an OS where it produces a genuine signal, I'm happy with the answer. I should really have thought of that myself… (Instructions like 6 won't work for a crash in this situation because it's running a different instruction set from the x86_64 solutions, but you might be able to get this down to one byte by finding a single-byte instruction that isn't in the instruction set used for DOS programs.)

The lock prefix (0xF0) generates #UD in front of most instructions (that is, everything that isn't an atomic read-modify-write on a memory destination). Given that program memory is loaded in pages, there will be more to read after lock, and a 0xF0 byte is almost guaranteed to generate #UD. But only almost, so not a solution.
Haven't found anything else yet.

C (32-bit Windows), 34 bytes
f(i){(&i)[-1]-=9;}main(){f(2831);}

This only works if compiling without optimizations (else, the illegal code in the f function is "optimized out").
Disassembly of the main function looks like this:
68 0f 0b 00 00    push 0b0f
e8 a1 d3 ff ff    call _f
...

We can see that it uses a push instruction with a literal value 0b0f (little-endian, so its bytes are swapped). The call instruction pushes a return address (of the ... instruction), which is situated on the stack near the parameter of the function. By using a [-1] displacement, the function overrides the return address so it points 9 bytes earlier, where the bytes 0f 0b are.
These bytes cause an "undefined instruction" exception, as designed.

Java, 50 43 24 bytes
a->a.exec("kill -4 $$");

This is a java.util.function.Consumer<Runtime>1 whose command is stolen from fluffy's answer. It works because you must call it as whateverNameYouGiveIt.accept(Runtime.getRuntime())!
Note that this will create a new process and make it throw a SIGILL rather than throwing a SIGILL itself.
1 - Technically, it can also be a java.util.function.Function<Runtime, Process> because Runtime#exec(String) returns a java.lang.Process which can be used to control the process you just created by executing a shell command.

For the sake of doing something more impressive in such a verbose language, here's a 72 60 48-byte bonus:
a->for(int b=0;;b++)a.exec("sudo kill -s 4 "+b);

This one is another Consumer<Runtime> that goes through ALL processes (including itself), making each of them throw a SIGILL. Better brace for a violent crash.

And another bonus (a Consumer<ANYTHING_GOES>), which at least pretends to throw a SIGILL in 20 bytes:
a->System.exit(132);

Perl, 9 bytes
kill+4,$$

Simply calls the appropriate library function for signalling a process, and gets the program to signal itself with SIGILL. No actual illegal instructions are involved here, but it produces the appropriate result. (I think this makes the challenge fairly cheap, but if anything's allowed, this is the loophole you'd use…)

Came here to post the same, with a space instead of the +. :)

When people learn Perl for non-golf programming, they learn it with a +. After golfing for a while, they do + occasionally to show off. Eventually, they've written enough programs where they needed to avoid whitespace for some reason or other that the + becomes habit. (It also parses less ambiguously, because it works around triggering the special case in the parser for parentheses.)

Using the "0" pid option from another example we can apparently shave off another byte. perl -E'kill+4,0'

ARM Unified Assembler Language (UAL), 3 bytes
nop

For example:
$ as ill.s -o ill.o
$ ld ill.o -o ill
ld: warning: cannot find entry symbol _start; defaulting to 00010054
$ ./ill
Illegal instruction

After executing nop, the processor interprets the .ARM.attributes section as code and encounters an illegal instruction somewhere there:
$ objdump -D ill

ill:     file format elf32-littlearm

Disassembly of section .text:

00010054 <__bss_end__-0x10004>:
   10054:       e1a00000        nop                     ; (mov r0, r0)

Disassembly of section .ARM.attributes:

00000000 <.ARM.attributes>:
   0:   00001341        andeq   r1, r0, r1, asr #6
   4:   61656100        cmnvs   r5, r0, lsl #2
   8:   01006962        tsteq   r0, r2, ror #18
   c:   00000009        andeq   r0, r0, r9
  10:   01080106        tsteq   r8, r6, lsl #2

Tested on a Raspberry Pi 3.

Somehow this doesn't work on a Pi 2.

Microsoft C (Visual Studio 2005 onwards), 16 bytes
main(){__ud2();}

I can't easily test this, but according to the documentation it should produce an illegal instruction by intentionally trying to execute a kernel-only instruction from a user-mode program. (Note that because the illegal instruction crashes the program, we don't have to try to return from main, meaning that this K&R-style main function is valid. Visual Studio never having moved on from C89 is normally a bad thing, but it came in useful here.)

Can you compile for linux with VS2015? Because I do not think SIGILL is defined in Windows, is it?

Ruby, 13 bytes
`kill -4 #$$`

I guess it's safe to assume that we are running this from a *nix shell. The backtick literals runs the given shell command. $$ is the running Ruby process, and the # is for string interpolation.

Without calling the shell directly:
Ruby, 17 bytes
Process.kill 4,$$

ELF + x86 machine code, 45 bytes
This should be the smallest executable program on an Unix machine that throws SIGILL (due to Linux not recognizing the executable if made any smaller).
Compile with nasm -f bin -o a.out tiny_sigill.asm, tested on an x64 virtual machine.
Actual 45 bytes binary:
0000000 457f 464c 0001 0000 0000 0000 0000 0001

0000020 0002 0003 0020 0001 0020 0001 0004 0000

0000040 0b0f c031 cd40 0080 0034 0020 0001

Assembly listing (see source below):
;tiny_sigill.asm
BITS 32

            org     0x00010000

            db      0x7F, "ELF"             ; e_ident
            dd      1                                       ; p_type
            dd      0                                       ; p_offset
            dd      $$                                      ; p_vaddr
            dw      2                       ; e_type        ; p_paddr
            dw      3                       ; e_machine
            dd      _start                  ; e_version     ; p_filesz
            dd      _start                  ; e_entry       ; p_memsz
            dd      4                       ; e_phoff       ; p_flags

_start:
                ud2                             ; e_shoff       ; p_align
                xor     eax, eax
                inc     eax                     ; e_flags
                int     0x80
                db      0
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
                db      1                       ; e_phnum
                                                ; e_shentsize
                                                ; e_shnum
                                                ; e_shstrndx

  filesize      equ     $ - $$

Disclaimer: code from the following tutorial on writing the smallest assembly program to return a number, but using opcode ud2 instead of mov:
http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html

I was gonna post a modified executable of that exact tutorial, but you beat me to it. This deserves to win; It's a true minimalist in the system resources sense (It requires no more than 45 bytes both in-file and in-memory, and is exactly the same in both), and no bloated interpreter like the other assembler solutions. It simply is what it is.

AutoIt, 93 bytes
Using flatassembler inline assembly:
#include<AssembleIt.au3>
Func W()
_("use32")
_("ud2")
_("ret")
EndFunc
_AssembleIt("int","W")

When run in SciTE interactive mode, it'll crash immediately. The Windows debugger should popup for a fraction of a second. The console output will be something like this:
--> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop
0x0F0BC3
!>14:27:09 AutoIt3.exe ended.rc:-1073741795

Where -1073741795 is the undefined error code thrown by the WinAPI. This can be any negative number.
Similar using my own assembler LASM:
#include<LASM.au3>
$_=LASM_ASMToMemory("ud2"&@CRLF&"ret 16")
LASM_CallMemory($_,0,0,0,0)

Any shell (sh, bash, csh, etc.), any POSIX (10 bytes)
Trivial answer but I hadn't seen anyone post it.
kill -4 $$

Just sends SIGILL to the current process. Example output on OSX:
bash-3.2$ kill -4 $$
Illegal instruction: 4

You could do kill -4 1 if the question isn't specific about which program throws the SIGILL

@MarkKCowan Heh, good point, although that assumes root...

You will have root in your programs - knock a byte off your answer and troll the question slightly at the same time :D.  BONUS: You get to kill init

@MarkKCowan: On (modern versions of?) Linux, init is actually immune to signals that it hasn't specifically requested to receive, even with root. You could perhaps work around this by using a different POSIX OS, though.

kill -4 2 then :D

@MarkKCowan ah, I missed the 'you will have root' stipulation. That certainly makes it easier!

@MarkKCowan PID 2 is kthreadd, which is a kernel thread and, like, init, can't receive signals unless it has registered for them specifically.

NASM, 25 bytes
I don't know how this works, just that it does on my computer specifically (Linux x86_64).
global start
start:
jmp 0

Compile & run like:
$ nasm -f elf64 ill.asm && ld ill.o && ./a.out
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080
Illegal instruction

You can probably shorten it to four bytes, as ja 0

or three as ud2

Probably because it's trying to jump to some data?

Python, 32 bytes
from os import*;kill(getpid(),4)

Same byte count: import os;os.kill(os.getpid(),4)

TI-83 Hex Assembly, 2 bytes
PROGRAM:I
:AsmPrgmED77

Run as Asm(prgmI). Executes the illegal 0xed77 opcode. I count each pair of hex digits as one byte.

Linux shell, 9 bytes
kill -4 0

Sends SIGILL to the process with PID 0. I don't know what process has PID 0, but it always exists.
Try it online!

From man kill: 0      All processes in the current process group are signaled.

x86 .COM, 1 byte
c

ARPL causes #UD in 16-bit mode

Rust, 53 bytes
fn main(){unsafe{std::hint::unreachable_unchecked()}}

This piece of code generates no main function because main is marked as unreached, hence SIGILL being triggered when run. Try it online!

Welcome to Code Golf and Programming Puzzles stack exchange! You have a nice first answer, but is preferable to add a link to try it online. Also, your answer is only 53 bytes long.

GNU C, 24 19 18 bytes
-4 thanks to Dennis
-1 thanks to ceilingcat
main(){goto*&"'";}

Try it online! This assumes ASCII and x86_64. It attempts to run the machine code 27, which ... is illegal.

shortC, 10 5 4 bytes
AV"'

Equivalent to the GNU C code above. Try it online!

L"\6" is also illegal, assuming x86_64.

@Dennis What instruction is 0x06? Also, the L is not necessary.

It's unassigned.

It's unassigned; that's what makes it illegal. Also, ' is 39 = 0x27, not 0x39.

MachineCode on x86_64, 2 1 bytes
7

Try it online!
Simply calls the x86_64 instruction 0x07 (ceilingcat suggested 0x07 instead of 0x27)

MMIXAL, 13 bytes
Main RESUME 2
RESUME is legal in all code; RESUME 1 throws a protection violation in user mode; any other argument throws an illegal instruction violation.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Efficient Typing on a Game Boy
Many old Game Boy games often required string input from the user. However, there was no keyboard. This was handled by presenting the user with a "keyboard screen" like so:

The 'character pointer' would begin on letter A. The user would navigate to each desired character with the D-Pad's four buttons (UP, DOWN, LEFT and RIGHT), then press BUTTON A to append it to the final string.
Please note:

The grid wraps around, so pressing UP whilst on letter A would take you to T.
The 'character pointer' stays put after appending a letter

The Challenge
The above keyboard has options to change case and is an irregular shape. So, for simplicity, in this challenge we will use the following keyboard (the bottom right is ASCII char 32, a space):
A B C D E F G
H I J K L M N
O P Q R S T U
V W X Y Z .

Typing on keyboards like this is extremely slow - so, to make this easier, your task is to write a program which tells the user the fastest possible way to type a given string. If there are multiple fastest ways, you only need to show one.
The output key should be:

> for RIGHT
< for LEFT
^ for UP
v for DOWN
. for BUTTON A (append current letter to string)

For example, when given the string DENNIS, the solution would look like this:
>>>.>.>>v..>>.>>>v.

Rules / Details

Please remember, the grid wraps around!
You may submit a full program or a function, as long as it takes the initial string and produces a solution string. Whitespace / trailing newlines are irrelevant as long as the output is correct.
You can assume input will only consist of characters typable on the specified keyboard, but it may be empty.
This is code-golf, so the shortest code wins. Standard code-golf loopholes apply.

Test Cases
There are usually multiple solutions of the same length. For each test case, I've included the optimum length, and an example. You don't need to print the length in your answer, just the solution.
FLP.TKC  ->  25 steps:  <<.<v.<<<v.<<<v.^.<<^.<^.
MOYLEX   ->  23 steps:  <<v.>>v.>>>v.>^^.^.<<^.
FEERSUM  ->  18 steps:  <<.<..<vv.>.>>.<^.
MEGO     ->  14 steps:  <<v.<^.>>.>vv.

A CAT    ->  17 steps:  .<^.>>>v.<<.<<vv.
BOB      ->  10 steps:  >.<vv.>^^.

(space)  ->  3 steps:   <^.
(empty)  ->  0 steps:   (empty)

You can view my testcase generator on repl.it - please notify me if there are any bugs.
Thank you everyone for the submissions! User ngn is currently the winner with 61 bytes, but if anyone can find a shorter solution, the little green tick can be moved ;)

Note that this has been through the sandbox, and a similar challenge was found, but discussion in chat and sandbox led to the conclusion that's it's not a dupe, just closely related :)

I thought it seemed very familiar, but it's not a duplicate of this one either.

Dyalog APL, 61 bytes
4 7∘{∊'.',⍨⍉↑b⍴¨¨'^v' '<>'⌷¨⍨⊂¨a>b←a⌊⍺-a←⍺|↓2-/0,⍺⊤⍵⍳⍨⎕a,'.'}
assumes ⎕IO←0
⎕a,'.' the alphabet followed by a full stop
⍵⍳⍨ find the argument's chars there as indices 0..26 (' ' and all others will be 27)
⍺⊤ encode in base 7 (note the left arg ⍺ is bound to 4 7), get a 2×n matrix
0, prepend zeros to the left
2-/ differences between adjacent columns
↓ split the matrix into a pair of vectors
a←⍺| take them modulo 4 and 7 respectively, assign to a
b←a⌊⍺-a make b the smaller of a and its modular inverse
'^v' '<>'⌷¨⍨⊂¨a>b choose ^ or v for the first vector and < or > for the second, based on where a differs from b
b⍴¨¨ repeat each of those b times
⍉↑ mix the two vectors into a single matrix and transpose it, get an n×2 matrix
'.',⍨ append .-s on the right
∊ flatten

JavaScript (ES6), 147 bytes
s=>s.replace(/./g,c=>(q=p,p="AHOVBIPWCJQXDKRYELSZFMY.GNU ".indexOf(c),"<<<>>>".substring(3,((p>>2)+10-(q>>2))%7)+["","v","vv","^"][p-q&3]+"."),p=0)

An interesting behaviour of substring is that it exchanges the arguments if the second is less than the first. This means that if I calculate the optimal number of left/right presses as a number between -3 and 3, I can add 3, and take the substring of <<<>>> starting at 3 and I will get the correct number of arrows. Meanwhile the down/up presses are simply handled by looking up an array using a bitwise and of the difference in rows with 3; this way is slightly shorter as there are fewer array elements.

Ruby, 107 bytes
->s{c=0
s.tr(". ","[\\").bytes{|b|b-=65
print ["","^","^^","v"][c/7-b/7],(d=(c-c=b)%7)>3??>*(7-d):?<*d,?.}}

Ungolfed in test program
f=->s{                                 #Input in s.
  c=0                                  #Set current position of pointer to 0.
  s.tr(". ","[\\").                    #Change . and space to the characters after Z [\
  bytes{|b|                            #For each byte b,
    b-=65                              #subtract 65 so A->0 B->1 etc.
    print ["","^","^^","v"][c/7-b/7],  #Print the necessary string to move vertically.
    (d=(c-c=b)%7)>3?                   #Calculate the horizontal difference c-b (mod 7) and set c to b ready for next byte.
       ?>*(7-d):?<*d,                  #If d>3 print an appropriate number of >, else an appropriate number of <.
    ?.                                 #Print . to finish the processing of this byte.
  }
}

#call like this and print a newline after each testcase
f["FLP.TKC"];puts
f["MOYLEX"];puts
f["FEERSUM"];puts
f["MEGO"];puts
f["A CAT"];puts
f["BOB"];puts

Python 2, 298 bytes
This is longer than it should be, but...
def l(c):i="ABCDEFGHIJKLMNOPQRSTUVWXYZ. ".index(c);return[i%7,i/7]
def d(f,t,a=abs):
 v,h=l(t)[1]-l(f)[1],l(t)[0]-l(f)[0]
 if a(h)>3:h=h-7*h/a(h)
 if a(v)>2:v=v-4*v/a(v)
 return'^v'[v>0]*a(v)+'<>'[h>0]*a(h)
s="A"+input()
print''.join([d(p[0],p[1])+'.'for p in[s[n:n+2]for n in range(len(s))][:-1]])

Any help would be greatly appreciated!
Takes input in quotation marks.
l returns the location of a character in the keyboard.
The two if statements in the middle of d are for checking if it would be optimal to 'wrap' around the keyboard.
The input, s has "A" prepended to it because the initial position of the cursor is A.
We loop through the string in pairs, discarding the last one (which is not a pair: [:-1]), finding the minimum distance between the two halves of the pair.
Thanks to Flp.Tkc for telling me that I can do a=abs instead of saying abs every time!

Mathematica, 193 bytes
Golf
StringJoin@@(StringTake[">>><<<",Mod[#〚2〛,7,-3]]<>StringTake["vv^",Mod[#〚1〛,4,-1]]<>"."&/@Differences[FirstPosition[Partition[ToUpperCase@Alphabet[]~Join~{"."," "},7],#]&/@Characters["A"<>#]])&

Readable
In[1]:= characters = ToUpperCase@Alphabet[]~Join~{".", " "}

Out[1]= {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ".", " "}

In[2]:= keyboard = Partition[characters, 7]

Out[2]= {{"A", "B", "C", "D", "E", "F", "G"}, {"H", "I", "J", "K", "L", "M", "N"}, {"O", "P", "Q", "R", "S", "T", "U"}, {"V", "W", "X", "Y", "Z", ".", " "}}

In[3]:= characterPosition[char_] := FirstPosition[keyboard, char]

In[4]:= xToString[x_] := StringTake[">>><<<", Mod[x, 7, -3]]

In[5]:= yToString[y_] := StringTake["vv^", Mod[y, 4, -1]]

In[6]:= xyToString[{y_, x_}] := xToString[x] <> yToString[y] <> "."

In[7]:= instructionsList[input_] := xyToString /@ Differences[characterPosition /@ Characters["A" <> input]]

In[8]:= instructions[input_] := StringJoin @@ instructionsList[input]

In[9]:= instructions["DENNIS"]

Out[9]= ">>>.>.>>v..>>.>>>v."

Java 8, 1045 bytes
Golf
staticchar[][]a={{'A','B','C','D','E','F','G'},{'H','I','J','K','L','M','N'},{'O','P','Q','R','S','T','U'},{'V','W','X','Y','Z','.',''}};staticintm=Integer.MAX_VALUE;staticStringn="";staticboolean[][]c(boolean[][]a){boolean[][]r=newboolean[4][];for(inti=0;i<4;i)r[i]=a[i].clone();returnr;}staticvoidg(inti,intj,boolean[][]v,chard,Stringp){v[i][j]=true;if(a[i][j]==d&&p.length()<m){m=p.length();n=p;}if(i-1<0){if(!v[3][j])g(3,j,c(v),d,p"^");}elseif(!v[i-1][j])g(i-1,j,c(v),d,p"^");if(i1>3){if(!v[0][j])g(0,j,c(v),d,p"v");}elseif(!v[i1][j])g(i1,j,c(v),d,p"v");if(j-1<0){if(!v[i][6])g(i,6,c(v),d,p"<");}elseif(!v[i][j-1])g(i,j-1,c(v),d,p"<");if(j1>6){if(!v[i][0])g(i,0,c(v),d,p">");}elseif(!v[i][j1])g(i,j1,c(v),d,p">");}publicstaticvoidmain(String[]args){boolean[][]v=newboolean[4][7];Scannerx=newScanner(System.in);Strings=x.next();Stringpath="";intp=0;intq=0;for(inti=0;i<s.length();i){chart=s.charAt(i);g(p,q,c(v),t,"");path=n".";n="";m=Integer.MAX_VALUE;for(intj=0;j<4;j){for(intk=0;k<7;k){if(a[j][k]==t){p=j;q=k;}}}}System.out.println(path);}

Readable
static char[][] a = {
        {'A','B','C','D','E','F','G'},
        {'H','I','J','K','L','M','N'},
        {'O','P','Q','R','S','T','U'},
        {'V','W','X','Y','Z','.',' '}
};
static int m = Integer.MAX_VALUE;
static String n="";

static boolean[][] c(boolean[][] a){
    boolean [][] r = new boolean[4][];
    for(int i = 0; i < 4; i++)
        r[i] = a[i].clone();
    return r;
}

static void g(int i, int j,boolean[][] v,char d,String p) {

    v[i][j] = true;
    if (a[i][j]==d && p.length()<m){
        m=p.length();
        n=p;
    }

    if (i-1<0) {
        if(!v[3][j])
            g(3, j, c(v), d, p + "^");
    }
    else if (!v[i-1][j])
        g(i-1, j, c(v), d, p + "^");

    if (i+1>3) {
        if(!v[0][j])
            g(0, j, c(v), d, p + "v");
    }
    else if(!v[i+1][j])
        g(i+1, j, c(v), d, p + "v");

    if (j-1<0) {
        if(!v[i][6])
            g(i, 6, c(v), d, p + "<");
    }
    else if (!v[i][j-1])
        g(i, j-1, c(v), d, p + "<");

    if (j+1>6) {
        if (!v[i][0])
            g(i, 0, c(v), d, p + ">");
    }
    else if (!v[i][j+1])
        g(i, j+1, c(v), d, p + ">");

}

public static void main(String[] args) {
    boolean[][] v = new boolean[4][7];
    Scanner x = new Scanner(System.in);
    String s = x.next();
    String path="";
    int p=0;
    int q=0;
    for(int i=0;i<s.length();i++){
        char t=s.charAt(i);
        g(p,q,c(v),t,"");
        path+=n+".";
        n="";
        m=Integer.MAX_VALUE;
        for(int j=0;j<4;j++){
            for(int k=0;k<7;k++){
                if(a[j][k]==t) {
                    p=j;
                    q=k;
                }
            }
        }

    }
    System.out.println(path);
}

Explanation
The solution is a direct approach: poorly optimized brute force. The method g(...) is a basic depth first search going through each permutation (up, down, left, right). With some slight modifications in ordering for the test cases I get the output:
<<.v<.v<<<.v<<<.^.^<<.^<.
v<<.v>>.v>>>.^^>.^.^<<.
<<.<..^^<.>.>>.^<.
v<<.^<.>>.^^>.
.^<.v>>>.<<.^^<<.
>.^^<.^^>.
^<.
// new line for the last

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Japanese Mahjong Score Calculator
I'm new to Japanese Mahjong and have trouble calculating the scores. Please help me write a program to calculate it.
Introduction
(aka you can skip this boring part)
Mahjong is a popular tile game in Asia. Different rules have evolved and systematically established in various regions. Japan, being an isolated island state, have its own mahjong variant including rules and scoring.
In Japanese Mahjong, 4 players participate in the game at the same time. They take turn to draw a tile from wall and discard a tile from hand. Occasionally then can take other's discarded tiles for use. Each round 1 of the 4 players will be the dealer. Independent of that, each round may have a winner if he/she can assemble a winning hand. There could be no winners in a round but we don't care about that in this challenge.
When a player become the winner of that round, the change in score is calculated depending on 4 things: (1) Han and (2) fu depends on the winning hand, (3) whether the winner is also a dealer, and (4) whether he win by self-draw or from other's discard. The winner get his points by taking the points from the losers. So points lost by all losers added should equal to points gained by winner. Moreover, sometimes only one loser lose his points while the other two don't lose any, and sometimes one of the three losers lose more points. (See below)
Objective
Write a program or function that accepts the 4 parameters mentioned above, and return (1) how many points the winner will gain, and (2-4) how many points each of the three losers will lose.
Details of inputs
Han: An integer from 1 to 13 inclusive.
Fu: An integer that is either 25, or an even number from 20 to 130 inclusive. If han is 1 or 2, fu is further capped at 110.
dealer or not: A truthy/falsy value. Though if you are a mahjong lover you can instead accept the winner's seat-wind :-)
self-draw or discard: A two-state value. Truthy/falsy value will suffice but other reasonable values are acceptable.
Steps of calculating the points gained/lost:
1. Calculate the base score
The base score is calculated based on 2 cases.
1a) Han ≤ 4
If fu is 25, then keep it as-is. Otherwise round it up to nearest 10.
Then base score is calculated by
base_score = fu×2han+2
And it's capped at 2000 points.
1b) Han ≥ 5
Fu is not used here. The base score is obtained by direct lookup of han in the following table:
Han    Base score
5      2000
6-7    3000
8-10   4000
11-12  6000
13     8000

2. Calculate the points lost by losers
2a) Dealer wins by self-draw
Each loser pays an amount equal to double of the base score, then rounded up to nearest 100.
2b) Dealer wins by discard
The discarding loser pays an amount equal to 6x the base score, then rounded up to nearest 100. Other two losers don't pay.
2c) Non-dealer wins by self-draw
Dealer (one of the loser) pays an amount equal to double of the base score, then rounded up to nearest 100. The other two losers each pays an amount equal to base score, also rounded up to 100.
2d) Non-dealer wins by discard
The discarding loser pays an amount equal to 4x the base score, then rounded up to 100. Other two losers don't need to pay. Scoring isn't affected by whether the discarding loser is dealer or not.
3. Calculate the points gained by winner
Winner gains the total points lost by the three losers. Not a point less and not a point more.
Example
(Some examples are shamelessly taken/modified from Japanese Wikipedia page of calculating mahjong score)
4 han 24 fu, dealer win by self-draw
24 fu rounded up to 30 fu
Base score = 30 × 2 4+2 = 1920
Each loser pays 1920×2 = 3840 => 3900 (rounded)
Winner takes 3900×3 = 11700 points
Output: +11700/-3900/-3900/-3900
3 han 25 fu, dealer win by discard
25 fu no need to round up
Base score = 25 × 2 3+2 = 800
Discarding loser pays 800×6 = 4800
Non-discarding loser pays 0 points
Winner takes 4800 points
Output: +4800/-4800/0/0
4 han 40 fu, non-dealer win by self-draw
40 fu no need to round up
Base score = 40 × 2 4+2 = 2560 => 2000 (capped)
Dealer pays 2000×2 = 4000
Non-dealer pays 2000
Winner takes 4000+2000×2 = 8000 points
Output: +8000/-4000/-2000/-2000
9 han 50 fu, non-dealer win by discard
Fu not used to calculate score
Base score = 4000 (table lookup)
Discarding loser pays 4000×4 = 16000
Non-discarding loser pays 0 points
Winner takes 16000 points
Output: +16000/-16000/0/0
Output
Output 4 numbers: The point that the winner is gaining (as positive number), and the points that each of the three losers is losing (as negative number).
You may output the numbers as 4 individual numerical values in your language's native format, an array/list of numbers, 4 separate strings (or array/list of characters), or a string contatining the numbers that are properly delimited. If you use string, the positive sign is optional but negative sign is mandatory.
The order of the numbers doesn't matter, since they can be inferred from sign and magnitude of the numbers. e.g. 0/-16000/+16000/0 is acceptable.
Format

Full program or function
Any reasonable input/output format
Default rules apply. Standard loopholes forbidden. code-golf so fewest bytes wins.

Notes

All outputs are guaranteed to be integers, more specifically multiples of 100 in the range [-48000,+48000]
Rounding is applied only to (1) fu and (2) loser's points. It is not applied to base score.
Theoretically winning by self-draw or discard should gain the same points (6x or 4x base points). However due to rounding, this may not be true at low han. (See 1st and 2nd test cases)

Test cases
(Also see example)
Inputs                         Outputs
Han    Fu     Dealer  Self     Winner   Loser1    Loser2    Loser3
1      22     N       Y        +1100    -500      -300      -300
1      22     N       N        +1000    -1000     0         0
3      106    Y       N        +12000   -12000    0         0
4      20     N       Y        +5200    -2600     -1300     -1300
4      25     Y       N        +9600    -9600     0         0
5      88     Y       Y        +12000   -4000     -4000     -4000
7      25     Y       Y        +18000   -6000     -6000     -6000
12     64     N       N        +24000   -24000    0         0
13     130    Y       N        +48000   -48000    0         0

Just spent a few hours for a C#6 answer but it's over 200 bytes. I will further golf it and post it after others have a chance to.

05AB1E, 79 bytes
05AB1E uses CP-1252 encoding.
Input order:
Han
Fu
Dealer = 1, Non-dealer = 0
Self = 2, Discard = 0

Code:
3‹i6b‚ï{0è}¹5‹iÐT/îT*‚sÈè¹Ìo*3°·‚{0èë\•j¤È°•¹è3°*}U•é2TˆÞ•S3ôŠ+èX*Tn/îTn*(DOÄ¸ì

Try it online!
Explanation to come.

Python 2, 128 bytes
def m(h,f,o,t):C=100;b=[24/(50/h)*1000,min(2000,[-f/10*~9,f][f%2]<<h+2)][h<5];x=(o|2-t)*-2*b/C*C;y=~o*t*b/C*C;return-x-y-y,x,y,y

h is han, f is fu, o is dealer (1/0), t is self-draw (1/0). Outputs in the same order as the test cases. ideone link.
Expanded slightly:
def m(h,f,o,t):
  C = 100

  # Base score
  b = [24/(50/h)*1000, min(2000,[-f/10*~9,f][f%2]<<h+2)][h<5]

  # Player scores - uses the -x/100*-100 approach to round up
  x = (o|2-t)*-2*b/C*C
  y = ~o*t*b/C*C

  return -x-y-y, x, y, y

Indirect thanks to @MartinEnder.

C#6, 211 bytes
using static System.Math;(h,f,x,y)=>{int b=h>5?24/(50/h)*100:Min(f%2<1?(int)Ceiling(f*.1)<<h+2:10<<h,200),c=-(int)Ceiling(b*.1*(y?2:x?6:4))*100,d=-(int)Ceiling(b*.1*(y?x?2:1:0))*100;return new[]{-c-d*2,c,d,d};};

Contains an idea shamelessly stolen from @Sp3000.
Assign to Func<int,int,bool,bool,int[]>
h=han
f=fu
x=true if dealer wins, false if non-dealer wins
y=true if self draw, false if discard
returns int[], [0]=winner, [1]-[3]:loser
repl.it demo
Ungolfed + explanations
// b is base score / 10
int b=h>5
    // han is [6,13], use Sp3000's idea
    ?24/(50/h)*100
    // han <= 5, calculate base score (/ 10) from formula...
    // Yes this formula works for han==5 also
    :Min(
        f%2<1
            // round up to 10, then times 2^(h+2)
            ?(int)Ceiling(f*.1)<<h+2
            // b=2.5*2^(h+2)=10*2^h=10<<h
            :10<<h
        // Cap at 200, thus base score is capped at 2000
        ,200),
// Multiply 0.1b by 2/4/6 according to input, then multiply by 100 to get actual score
c=-(int)Ceiling(b*.1*(y?2:x?6:4))*100,
d=-(int)Ceiling(b*.1*(y?x?2:1:0))*100;
// Array type implied from arguments
return new[]{-c-d*2,c,d,d};

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Draw a Dragon Curve
You task for today: draw a dragon curve!
In case you don't know what a Dragon Curve is, here is an introductory ViHart video (Really cool, please watch!)
Your task: draw a dragon curve, iterated at least 9 times. You don't have to show iterations 1 through 9, you just have to show the final curve produced after completing (at least) 9 iterations. The curve must be drawn as straight lines connecting the points on the curve; the output should match one of the images below that shows 9 or more iterations (up to reflection, rotation, scaling, and variation in line width, line color, and background color). Your output must be large enough that the individual lines and the "boxes" that they form can be distinguished from each other; if two lines don't intersect in the curve, they shouldn't occupy the same or adjacent pixels in the output (there should be at least one pixel of the background visible between them). You can either display the image to the screen or saved the image to a file is accepted. The output must be graphical - it can't be ASCII art.
The shortest code in bytes wins, however include directives for libraries shouldn't be included in the byte count, and you may use graphics libraries or other libraries written for your language of choice if they were written before the posting.
Please include an image of the output of your program.

Skip this paragraph if you watched the video: For those of you who decided not to watch the video, the first 12 iterations of the dragon curve are shown below. For the purposes of this task, a dragon curve is a curve generated by the following rule: take the end-point of the current curve, create a second curve rotated 90 degrees around that end-point so that the end-point of the original curve is the starting point of the new curve, and join the two curves into a single curve where they meet. In the images shown below, each new iteration is generated by rotating the previous iteration 90 degrees clock-wise around the end-point each iteration. When the curve is displayed on the screen, it's not obvious which end counts as the "end-point", however when the curve is stored as a array of points, it's easy to define the "end-point" as the last point in the array.
Ascii art is appreciated, but not accepted: This is graphical output, not ascii-art.

Are there any specifications about sizing, coloring, etc? As it is the exact output is a bit unclear.

Related.

And you don't actually explain what a dragon curve is either, you just show some examples.

I removed the [tag:dragon-curve] tag because it didn't seem to add anything

Also related.

Added specifications about sizing, colouring, etc

@MartinEnder Can you explain how the thue-morse sequence is related to the dragon curve? It´s not immediately apparent. The wikipedia page mentions fractals but only talks about koch curves.

@Oliver That was already flagged up by Fatalize (who by the way asked the previous question.) I think ASCII art is actually slightly more challenging than graphics in this case, so it could indeed be a duplicate, but I`m abstaining from voting.

@LevelRiverSt The constructions of the two sequences (representing left and right turns as 0s and 1s) are almost identical up to reversing part of the sequence when extending it. I've also found a claim online that they're closely related, but their sources were behind a paywall.

Because it's specifying that the output must be graphical and not ascii-art, I believe that it's valid and different from the one asking for ascii-art as output.

I'm concerned about a potential loophole in not counting library imports in the byte count. In at least Perl, you can give libraries arbitrary arguments when importing them, and there's probably some library that won't error out on arguments it doesn't understand and some way to figure out what those arguments were after the fact, meaning that the program could be encoded using import statements rather than written the "normal" way.

I would LOVE to see someone abuse the rules in such a convoluted way

@Jorge Perez - I loved the video (watched it a couple months back) and have coded a few dragon curves (HTML/Python). I've however not tried to golf it yet and think this is a great idea :)

Thanks you so much! I wanted a graphical version because I knew it could be shorter than the ascii version, and also because I liked the output better. I actually have an answer that's 97 bytes, but I'm saving it for a while until I see other people's answers

Can the scale of the two axes be different? So the squares are seen as rectangles

I'd accept that, although I'd find the square version to be much more aesthetically pleasing.

This is not a duplicate; the programming techniques to solve it are quite different (except in maybe Charcoal). Most of the answers use turtle graphics libraries, which wouldn't work in an ASCII context at all.

@ais523 not a duplicate, but the techniques are very similar. I used the same turtle graphic concepts here and in my ascii art version. It's still keeping track of x,y position of a moving pen with the right and left turns where needed.

Are built-ins/libraries permitted?

x86, MSDOS, 16 bytes
I wrote this a while ago, to my knowledge the smallest routine for producing a dragon fractal. It uses no real iterations, rather plots every contained discrete pixel inside the fractal directly, showing the final image. It's included with many other tiny productions in this pack. The 16 byte version was the end of my effort to get the dragon fractal as small as possible, starting 2014 with this 32 byte production.
Hex
14 10 19 CA D1 FA 10 DE 01 D1 CD 10 B4 0C EB F0

Code
S:
adc al,0x10
sbb dx,cx
sar dx,0x01
adc dh,bl
add cx,dx
int 0x10
mov ah,0x0C
jmp short S

This is... Amazing, to say the least. How would I go about running it?

The quickest way would be a DosBox online, http://twt86.co?c=FBAZytH6EN4B0c0QtAzr8A%3D%3D You can copy the source here and compile it yourself there. The classic way is to download DosBox (0.74) yourself and run it there. The most real way is to get a MSDos or FreeDos Bootstick (Rufus), and run it for real #noemu ;)

Python 2/3, 169 167 150 111 98 78 Bytes
Note that the import is not included in the byte count, according to the challenge specs.
Thanks to @AlexHall for saving 39(!) bytes and @nedla2004 for another 13
from turtle import*
o=[90]
for z in o*9:o+=[90]+[-x for x in o[::-1]]
fd(5)
for i in o:rt(i);fd(5)

Starts by generating a list or right (90) and left (-90) turns, then goes through the list and moves the turtle.
Generated Output:

EDIT: If this is too boring too watch, add speed(0) right before the first fd(5). It will run the same, except the turtle will move much faster.

A picture would be nice :)

Could you post a picture or screenshot of the output? It's not even clear that this code prints anything to the screen

Your image got cut off

Should be fixed now :)

@AlexHall Thanks! I knew there must have been a way to make that loop waaaay shorter :)

The program can be this, for 98 bytes, but will not actually run online.

Some of those byte savings are thanks to @nedla2004, not me :) I especially like the use of o*9.

@AlexHall Me too, I was originally going to create another variable with the value [90], but I realize this was shorter. :)

@nedla2004 What do you mean? Trinket.io supports turtles. https://trinket.io/python/14f1cb779e

This works also in Python 3

@LuisMendo Thanks. I will update the title to match.

I have never seen that page before, all I meant is that repl.it and Ideone will not work with turtle.

Two more bytes to be saved if you want: drop the line fd(5) and change the line that starts for i in o: to instead start for i in [0]+o:  This gets the fd(5) from the loop instead by adding a no-op 0 degree right turn.

can you do o=90, instead?

@Cyoce No. It needs to be a list because I then build on that list later and use it as my list of moves for the turtle.

Logo, 43 bytes
for[i 1 512][fd 9 lt :i/(bitand :i -:i)*90]

Try with interpreter at http://www.calormen.com/jslogo/#
This uses the same principle as my previous ASCII art answer and the formula on at wikipedia except I reversed the direction to match the image in the question:

First, express n in the form k*(2^m) where k is an odd number. The direction of the nth turn is determined by k mod 4 i.e. the remainder left when k is divided by 4. If k mod 4 is 1 then the nth turn is R L; if k mod 4 is 3 then the nth turn is L R

bitand :i -:i finds the least significant bit of i. We divide i by this to shitft i right the required amount, giving the required odd number k. There is no need to distinguish between left and right turns; we just turn left by k*90 degrees and rely on the fact that rotation is a modulo 360 operaton to perform the modulo for us.
Output
use ht to hide turtle if required.

Output (modified)
The following shows how the curve is a single strand.
bk 6 for[i 1 512][fd 6 rt :i/(bitand :i -:i)%4*45-90 fd 3 rt :i/(bitand :i -:i)%4*45-90]

Underload, 196 bytes
()()(<svg width="99" height="147">)S(<g transform="translate):S((33,33)">)S((3,0)rotate)*a(*a(~*)*~("><path d="M0h3" stroke="#"/>)~*a(*)**:(-90)a~^~(90)a~^)*::*:**:*^S(</g>)(:*)::*:**:*^S(</svg>)S

I thought it might be interesting to try this challenge in a low-powered esolang; Underload does fairly well for a language with such a low number of commands.
The output is an SVG file with very heavily nested tags, and some golfing shortcuts. So far, I haven't found a browser that can display it (Firefox hangs for several minutes trying to load it, and both Firefox and Chromium give a blank screen). Most image processing programs can't load it either (making it hard to convert to another format), but I managed to load it in the image viewer Eye of Gnome (which is part of the default install on Ubuntu). So I took a screenshot of the image so that you can see it (the actual image has a transparent background, but you can't really screenshot transparent):

We need to specify the image size explicitly. Picking an appropriate orientation for the image, drawing everything at the minimum legal size, and doing the minimum number of iterations specified by the challenge, gives us an image that just fits into 99 pixels wide, saving a byte. It's nice when things work out like that.
The general algorithm used for drawing the image is to maintain two variables (Underload doesn't name variables, but I thought of them as x and y), both initially empty. Then we repeatedly replace (x, y) with (x, turn left and move forward, y) and (x, turn right and move forward, y). After ten iterations, both x and y hold a nine-iteration dragon curve.
There are a few micro-optimizations and Underload-specific tricks, too. In order to avoid too much messing around with the top of the stack, each loop iteration, we start by combining x and y into the function "return the string created by concatenating: x, a turn instruction, the function argument, a move-forward instruction, and y." This function only takes up one space on the stack, so we can duplicate it, call it with -90 as an argument, swap the return value under the duplicate, and call it with 90 as an argument, to get hold of new values for x and y without ever needing to touch more than the top two elements of the stack (which are by far the most commonly accessible). This function is code-generated at runtime. The generator itself is also code-generated at runtime, in order to allow it to reuse the string <g transform="translate that's also used to set the origin of the image. We generate all the open tags first, and then because all the close tags are just </g>, we can output 1024 close tags via simply repeating the string, without worrying about matching them to the open tags. (Writing numbers efficiently in Underload is an interesting problem in its own right; (:*)::*:**:* is probably the most efficient way to write 1024, though, translating to "2 to the power of (1 + 2×2) × 2".
Underload doesn't have any graphics libraries, so I produce SVG using a combination of drawing lines in a fixed position, and rotating the image around a given point; instead of turning the pen, we turn the paper. The idea is that by drawing a line, rotating the entire image, drawing another line, rotating the image again, etc., we can effectively simulate turtle graphics without having to do any arithmetic or use any graphics libraries, as all the lines are drawn in the same location. Of course, that means that we have some very heavily nested rotate-the-image tags, which confuses many SVG viewers.
Styling the image would count against the byte count, so I needed to give the minimum styling needed to display the image. This turns out to be stroke="#", which more or less translates as "the line needs to be some color"; this seems to be expanded to drawing it in black. (Normally you'd specify the color as, say, "#000".) The background is transparent by default. We don't specify a stroke width, but the choice picked by Eye of Gnome leaves everything visible.
Many Underload interpreters struggle with this program, e.g. the one on Try It Online crashes, because it generates some very large strings internally. The original online Underload interpreter works, though. (Interestingly, the very first interpreter was online, so the language was usable online before it was usable offline.)
Something I'm slightly uneasy about is that there only seem to be 1023 line segments here, and we'd expect 1024. It could be that one of the segments at the end isn't being drawn with this algorithm (it'd be drawn on the next iteration instead). If that's disqualifying, it may be possible to adapt the program, but it might well end up considerably longer. (It's not like this challenge is going to win the competition anyway; there are already several shorter entries.)

LindenMASM, 51 Bytes
LindenMASM was a language I created for a challenge a while ago that will forever live in the Sandbox. It makes use of the concept of Lindenmayer systems to draw things like Dragon curves, fractal plants, Sierpinski triangles, etc.
The source code is as follows:
STT
AXI FX
INC 9
SET F 0
RPL X X+YF+
RPL Y -FX-Y
END

To set this up for n = 6 for example:
STT
AXI FX
INC 6
SET F 0
RPL X X+YF+
RPL Y -FX-Y
END

This produces the following image via Python 3's turtle:

There may be a slight numbering difference for iterations, as in the Lindenmayer system the first iteration is a single line. Here's what it looks like for n = 10:

Just for fun, here's what it looks like with 15 generations (with an added instruction MOV 2 to make it a bit smaller):

Once you get up to 20 generations (with MOV 0.5) you can't really see the lines anymore, and it takes a LOT of steps to create (pairs of +- and -+ are not optimized out). Here's what you get:

Note that the current interpreter may present graphical issues for smaller amounts of generations, i.e. possibly not drawing to the screen. Unfortunately when this interpreter was created there were no issues, a possible change in Python 3 could have caused this or it could just be my system

MATL, 26 bytes
0J1_h9:"tPJ*h]hYsXG15Y01ZG

If different scales in the two axes are accepted, the code can be reduced to 19 bytes:
0J1_h9:"tPJ*h]hYsXG

The figures below correspond to the equal-scale (26-byte) version.
The code above produces the 9-th (0-based) iteration, that is, the tenth image in the challenge:

For other values change the 9 in the code, or replace it by i to take the number as user input. For example, the result for 13 is:

Explanation
This uses a loop to gradually build an array of the steps followed by the curve in the complex plane. For example, the first two steps are 1j (up) and -1 (left).
In each iteration, the array of steps so far is copied. The copy of the array is reversed, multiplied by 1j (to rotate 90 degrees), and concatenated to the original.
After the loop, a cumulative sum of the steps gives the actual points, which are then plotted in the complex plane.
0                          % Push 0
 J1_h                      % Push array [1j, -1]. This defines the first two steps
     9:                    % Push [1, 2, ..., 9]
       "                   % For each
        t                  %   Duplicate the array of steps so far
         P                 %   Reverse
          J*               %   Multiply by 1j
            h              %   Concatenate horizontally to previous steps
             ]             % End
              h            % Concatenate with the initial 0
               Ys          % Cumulative sum
                 XG        % Plot. Complex numbers are plotted with real and imag as x and y
                   15Y0    % Push string 'equal'
                       1ZG % Set equal scale in the two axes

Your answer is impressive :) do you mind providing an explanation of the code?

@Jorge Thanks! Done

The "19-byte" and "26-byte" versions you provide are identical. I assume there's a copy-and-paste error here?

@ais523 Indeed! Corrected now, thank for noticing. BTW it can be seen in action here (experimental compiler; may require refreshing the page)

Python 2, 43 bytes
This answer is 43 bytes not including the import statement and it's largely based on Level River St's Logo answer and their use of i/(i&-i) in their code. Try it online at trinket.io
from turtle import*
for i in range(1,513):fd(9);rt(90*i/(i&-i))

Here is a picture of the output.

As far as I know, you need to include the byte count from the import statement in your total byte count.

@Theo, just quoting from the challenge specification: The shortest code in bytes wins, however include directives for libraries shouldn't be included in the byte count, and you may use graphics libraries or other libraries written for your language of choice if they were written before the posting.

Mathematica, 56 55 bytes
Graphics@Line@AnglePath[Pi/2JacobiSymbol[-1,Range@512]]

Explanation: OEIS A034947
Just for fun, here is a colored version of the 19th iteration.

Mathematica 86 bytes
{1,-1}
r=Reverse;Graphics@Line@Nest[Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&,{{0,0},%},9]

How it works:
{1,-1} Outputs {1,-1}. It basically "pushes it to the stack". This value can be recalled with %. r=Reverse basically just renames the Reverse function because I use it twice in the code. The Graphics@Line@ just takes a list of points and draws a line connecting them. The real meat of the problem happens in this code segment: Nest[Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&,{{0,0},%},9].
Lemme tell you - that segment is complicated as f******ck. Here's what Nest does: Nest[f,x,9]outputs the result of calling f[f[f[f[f[f[f[f[f[x]]]]]]]]].
In my code, this first argument f is: Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&, the second argument x is {{0,0},%} (which evaluates to {{0,0},{1,-1}}), and the third argument is n, which is just 9 (which will just apply the first argument to the second argument 9 times).
The most complex part of all is this first argument: Join[l=Last@#;h=#-l&/@#,r[r@#%&/@h]]&, which is a giant mess of almost pure syntactic sugar. I was really abusing mathematica's syntactic sugar for this one. That line of code represents mathematica's version of an anonymous function, except to shorten things I actually defined two separate anonymous functions within that anonymous function. Yep, that's legal, folks. Let's break it down.
Join takes two arguments. The first is l=Last@#;h=#-l&/@#, and the second is r[r@#%&/@h].
The first argument of Join: Inside the "main" anonymous function, # is a list of all the points at the current iteration in the curve. So l=Last@#; means "Take the point in the list of points you recieved as input, and assign that point to the variable l. The next segment, h=#-l&/@#, is a little more complex. It means "You have a function. This function takes a point as input, subtracts l from it, and returns the result. Now, apply that function to every element in the list of points you received as input to generate a list of shifted points, and assign that new list to the variable h.
The second argument of Join: r[r@#%&/@h] has literally the most complex syntax I've ever written. I can't believe any code segment could contain something like @#%&/@ - it looks like I'm cursing like a cartoon character in the middle of a program! But it's possible to break it down. Remember - r[x] takes a list of points and returns that list in reverse order. r@#%& is an anonymous function that reverses it's input, then multiplies it by the value storied in % (which is {1,-1}), and returns the result. Basically it rotates it's input 90 degrees, but in code as short as I could possibly write. Then r@#%&/@h means "Output a new list that is every point in h rotated 90 degrees."
So overall, Join[l=Last@#;h=#-l&/@#,r[r@#*%&/@h]]& is a function that takes a list of points as an input, and adds on that same list of points rotated 90 degrees to get the next iteration of the curve. This is repeated 9 times to get the dragon curve. Then it's the resulting list of points is drawn to the screen as a line. And the output:

I just found the weirdest trick for writing a null vector: 0{,} ... works because 0 x is 0 for almost any x and {,} is syntactic sugar for {Null,Null}.

HTML + JavaScript, 182

<canvas id=C></canvas><script>c=C.getContext("2d")
C.width=C.height=400
s=n=9
x=y=200
for(i=d=0;i<=1<<n;d+=++i/(i&-i))
c.lineTo(x,y),
d&1?y+=d&2?s:-s:x+=d&2?-s:s
c.stroke()</script>

Mathematica, 63 bytes
Using AnglePath
Graphics@Line@AnglePath[Pi/2Nest[Join[#,{1},-Reverse@#]&,{},9]]

Haskell + diagrams, 179 bytes
import Diagrams.Prelude
import Diagrams.Backend.SVG
d 1=hrule 1<>vrule 1
d n=d(n-1)<>d(n-1)#reverseTrail#rotateBy(1/4)
main=renderSVG"d"(mkWidth 99)$strokeT(d 9::Trail V2 Double)

Output is a 99 pixels wide svg file with transparent background (an image 9 pixels wide would have a stroke too thick to recoqnize anything). Here it is rescaled and composed over a white background:

tosh, 518 bytes
tosh is Scratch, but with text instead of blocks. At 518 bytes, this answer is probably even worse than Java.
This answer uses the same logic as @Theo's Python answer, but with strings of "L" and "R" instead of numbers, as Scratch's (and thus tosh's) list capabilities are awful.
You can run it as a Scratch project here. (tosh compiles to Scratch projects)
when flag clicked
set path to "R"
go to x: -50 y: 100
point in direction 90
pen down
set pen size to 2
clear
repeat 9
    set path copy to path
    set path to join (path) "R"
    set i to length of path copy
    repeat length of path copy
        if letter i of path copy = "R" then
            set path to join (path) "L"
        else
            set path to join (path) "R"
        end
        change i by -1
    end
end
set i to 0
repeat length of path
    change i by 1
    if letter i of path = "R" then
         turn cw 90 degrees
    else
         turn ccw 90 degrees
    end
    move 7 steps
end

Explanation:
when flag clicked
set path to "R"
go to x: -50 y: 100
point in direction 90
pen down
set pen size to 2
clear

This first part makes the program run when the green flag is clicked (when flag clicked), sets the path variable to "R", and gets the sprite and stage in the proper state to be ready to draw.
repeat 9
    set path copy to path
    set path to join (path) "R"
    set i to length of path copy
    repeat length of path copy
        if letter i of path copy = "R" then
            set path to join (path) "L"
        else
            set path to join (path) "R"
        end
        change i by -1
    end
end

Now we get to the path generation code. It uses the same logic as @Theo's Python answer, except with strings of "R" and "L" instead of numbers, and we use nested loops instead of list comprehensions.
set i to 0
repeat length of path
    change i by 1
    if letter i of path = "R" then
         turn cw 90 degrees
    else
         turn ccw 90 degrees
    end
    move 7 steps
end

Finally, we draw the path by going through each letter of the path variable and turning left or right depending on the letter.


text:
Distance Between Two Points Travelling on a Polar Graph Chart
Brief Problem Explanation
Write a program to find the minimum distance between two points traveling only on rays emanating from the origin and circles centered on the origin.
Explanation of Premise
Now let's imagine we are on a plane, and on this plane we are only allowed to travel in special ways. We are allowed to travel on any ray emanating from the origin.

We can also travel on any circle centered at a circle

Now our goal is to travel from one point on this plane to another. However, we can't just travel in a simple Euclidian path, we can only do this if the points happen to fall on a ray emanating from the center.

We can travel on this one because it falls on a one of our rays.

We can also travel on circles centered at the origin.

Examples
Now here is the challenge:
We've got to get from one point to another in the shortest path; often this is a combination of traveling on circles and rays.

This, however, it could also be traveling on two rays.

Sometimes there exist two paths that travel the minimum distance.

Problem
Your challenge is to write a program that when given two points will give us the minimum distance between them if we follow these rules. The inputs can be given in either rectangular or polar forms and the output ought to be one number, the distance between.
Test Cases
(with rectangular input)
(1,1) (1,-1) -> ~ 2.22144
(0,0) (1, 1) -> ~ 1.41421
(1,0) (-0.4161 , 0.90929) -> ~ 2
(1,1) (1, 0) -> ~ 1.19961
(1,2) (3, 4) -> ~ 3.16609

Are the example test cases in rectangular or polar forms? Also: bewteen

They are in the rectangular form, I ought to clarify that

Is the last example correct? I'm getting ~3.166

The Euclidean path is the limiting case of a series of ray and circle movements, so why is the output not going to be the Euclidean distance?

@Peter Taylor Because they are not really the same path. In a similar way a path from 0,0 to 1,1 on the xy plane via small steps alternating in the x and y directions appears identical to a direct diagonal path as the step length tends to zero. But the diagonal path has length sqrt(2) while the step path will always have length 2.

Can the input be two complex numbers?

@LuisMendo Sure!

Can we assume that the inputs will never be two of the same point, i.e. (1,1) (1,1)?

In other words, can the distance between the two input points ever be zero?

I think the challenge would look better if the images were not so large. Currently they make it hard to follow the text

@LuisMendo I agree, but I don't know how to do this without putting the images thru Photoshop and then replacing them, is there an easier way?

@R.Kap Yeah, I think that's a fair assumption especially for golf. But it shouldn't be too hard to make it work with a distance of 0

@AndoBando I haven't tried it, but appararently yes

Haskell, 49 48 bytes
(a!q)c r=min(q+r)$abs(q-r)+acos(cos$a-c)*min q r

Usage:
> let rect2polar (x,y)=(atan2 y x, sqrt(x^2+y^2))
> let test c1 c2=let [(a1,r1),(a2,r2)]=rect2polar<$>[c1,c2] in (a1!r1)a2 r2
> test (1,0) (-0.4161, 0.90929)
1.9999342590038496

Thanks to @Zgarb for saving a byte

You can save a byte by defining (a!q)c r instead of d a q c r.

JavaScript (ES6), 65 bytes
with(Math)(r,t,s,u,v=acos(cos(t-u)))=>v<2?abs(r-s)+v*min(r,s):r+s

Takes polar coordinates. Uses @Angs' trick for reducing an angle to between 0 and π. For rectangular coordinates, something like this works:
with(Math)g=(r,t,s,u,v=acos(cos(t-u)))=>v<2?abs(r-s)+v*min(r,s):r+s
with(Math)f=(x,y,v,w)=>g(hypot(y,x),atan2(y,x),hypot(w,v),atan2(y,v))

MATL, 22 bytes
|ttsGZ}/X/bX<*|bd|+hX<

Input is an array of two complex numbers.
Try it online! Or verify all test cases.
Explanation
|       % Implicitly input array and take absolute value of its entries
tt      % Duplicate twice
s       % Sum. This is the length of the path that follows the two radii
GZ}     % Push input again and split into the two numbers
/X/     % Divide and compute angle. This gives the difference of the angles
        % of the two points, between -pi and pi
bX<     % Bubble up a copy of the array of radii and compute minimum
*|      % Multiply and take absolute value. This is the arc part of the
        % path that follows one arc and the difference of radii
bd|     % Bubble up a copy of the array of radii and compute absolute
        % difference. This is the other part of the second path
+       % Add. This gives the length of second path
hX<     % Concatenate and take minimum to produce the smallest length.
        % Implicitly display

Ruby, 64 bytes
First, my submission. Lambda function with arguments distance 1, angle 1, distance 2, angle2.
->r,a,s,b{([d=(b-a).abs,?i.to_c.arg*4-d,2].min-2)*[r,s].min+s+r}

Now here's two different solutions of 66 bytes (excluding assignment f=) followed by my actual submission again at 64 bytes.
Solution 1:Using include Math, 66 bytes excluding f=
include Math;f=->r,a,s,b{[acos(cos(b-a)),2].min*[r,s].min+(s-r).abs}

Solution 2:Using complex number to define PI instead, 66 bytes excluding f=
f=->r,a,s,b{[d=(b-a).abs,?i.to_c.arg*4-d,2].min*[r,s].min+(s-r).abs}

SUBMISSION AGAIN, 64 bytes excluding f=
f=->r,a,s,b{([d=(b-a).abs,?i.to_c.arg*4-d,2].min-2)*[r,s].min+s+r}

The Submission is based on solution 2, but uses the identity (s-r).abs=s+r-[s,r].min*2 to shorten the code by 2 bytes, hence the -2 inside the brackets.
The other notable feature is the expression ?i.to_c.arg*4 = 2*PI without using include Math. If lower precision is acceptable this can be replaced by a literal.
Solution 2 commented in test program
f=->r,a,s,b{          #r,s are distances, a,b are angles for points 1 and 2 respectively.
    [d=(b-a).abs,       #From nearer point we can take arc of length d radians perhaps crossing zero angle to the ray of the further point
    ?i.to_c.arg*4-d,    #or go the other way round which may be shorter (?i.to_c.arg*4 == 2*PI, subtract d from this.)
    2].min*             #or go through the centre if the angle exceeds 2 radians.
  [r,s].min+          #Multiply the radians by the distance of the nearer point from the origin to get the distance travelled.
  (s-r).abs           #Now add the distance to move along the ray out to the further point.
}

#test cases per question (given as complex numbers, converted to arrays of [distance,angle]+[distance,angle] (+ concatenates.)
#the "splat" operator * converts the array to 4 separate arguments for the function.
p f[*("1+i".to_c.polar + "1-i".to_c.polar)]
p f[*("0".to_c.polar + "1+i".to_c.polar)]
p f[*("1".to_c.polar + "-0.4161+0.90929i".to_c.polar)]
p f[*("1+i".to_c.polar + "1".to_c.polar)]
p f[*("1+2i".to_c.polar + "3+4i".to_c.polar)]

Output
2.221441469079183
1.4142135623730951
1.9999342590038496
1.1996117257705434
3.1660966740274357

Mathematica 66 Bytes
This takes rectangular coordinates and can output an exact symbolic solution
Min[If[(m=Min[{p,q}=Norm/@#])>0,m*VectorAngle@@#,0]+Abs[p-q],p+q]&

Usage:
%/@{
{{1,1},{1,-1}},
{{0,0},{1,1}},
{{1,0},{-.4161,.90929}},
{{1,1},{1,0}},
{{1,2},{3,4}}
}

yields:

N@% yields:
{2.221441469, 1.414213562, 1.999934259, 1.199611726, 3.166096674}

Nifty! if you're going the symbolic route you can replace test case {1,0}{-.4161,.90929} with {1,0}{cos(2),sin(2)}

Python 2, 164 126 125 132 bytes:
def A(a,b,c,d,p=3.1415926535):z=abs(a-c);M=lambda f:2*p*f*abs(b-d)/360.0;print min((a==c)*min(a+c,M(a))+(b==d)*z or'',M(a)+z,M(c)+z)

I am currently looking into golfing this more, though. Accepts polar coordinates. Should be called in the format A(r1,θ1,r2,θ2). Outputs a floating point value accurate up to 12 significant figures.
Try It Online! (Ideone)
A simple, straightforward implementation that calculates and outputs to STDOUT the minimum value out of an array of at most 3 values containing:

the minimum value out of either the sum of the two lengths (r1+r2) or the length of the arc connecting the two points iff r1==r2;
the difference between the two distances (abs(r1-r2)) iff θ1==θ2 (i.e. the two points are collinear);
if none of the previous 2 items are added, then an empty string ('') as apparently in Python a string is greater than any integer;
and 2 final values given from the distances traveled along a circle and a ray and vice-versa between the two points.

Why not math.pi?

Wolfram Language (Mathematica), 47 bytes
MinMax@Abs@{##}.{Min[Abs[Arg@#-Arg@#2]-1,1],1}&

Try it online!
(beats the current 66-byte answer)
Take input as 2 complex numbers.
May have some issues if the input is symbolic. (e.g., Cos@2 + I Sin@2)


text:
The Almost-Eternity Code
Write a program that outputs as many characters as possible, with two conditions:

The program must be 256 bytes or shorter
The program must almost surely eventually halt. In other words, the only thing not permitted in response to this question is an infinite loop.

For the purposes of this problem, any built-in psudo-random number generators will be treated as though they actually produce true random numbers. Even if it takes a really long time (years, centuries, or millennia) to compile, the program MUST BE a valid program in your language (and it must compile in a finite amount of time).
The program which produces the longest textual output before halting wins!!! (This means you must provide an approximate number of the expected length of output).
A note on arbitrary-precision arithmatic: No use of built-in arbitrary precision arithmetic capabilities.

Why the restriction on less than 256 characters?

Because the easiest way to make the program produce a longer output is to just wrap the entire program in a giant tower of for loops:

In general, needing extra restrictions is a sign of a bad challenge. You probably shouldn't need that restriction.

If I don't limit the length of the code, someone's going to just give a giant tower of for-loops inside for-loops as they're response.

Yeah, but if that's a valid answer without the restriction then the premise of the challenge may be bad.

A giant tower of for-loops is an acceptable answer, as long as it's less than 256 bytes.

It's like a busy-beaver number with a turing machine. You can make arbitrarily complex turing machines to run for arbitrarily long amounts of time, but busy-beaver numbers are only interesting if you put a limit on the number of symbols and the number of states.

Let us continue this discussion in chat.

I don't see how this is off-topic. It definitely has an objective primary winning criterion (namely, most characters output). This isn't to say that this wouldn't be a duplicate of Largest Number Printable.

It's not a duplicate. The victory condition also appears to be objective (although some of the resulting numbers may be so high that they're hard to compare). I'd recommend you make some sort of statement about whether the program has to run on a physical computer (which would be subject to things like word size restrictions and the like) or not; it makes a huge amount of difference here! (256 bytes is probably enough to write a program that uses the entirety of the computer's memory as a counter, and it's mathematically impossible to produce more output than that without an infinite loop.)

I have a program that output approximately (on an infinite powered machine) 3.43E214 characters (tell me if you want the exact number, I got it). Written in C99, 256 bytes.

Correction, I can output 5.28E270 characters in C99, 256 bytes :)

The problem with this challenge is that if you allow randomness, it becomes difficult to compare two entries where the expected number of printed characters is infinite.

"The program which produces the longest textual output before halting wins!!! (This means you must provide an approximate number of the expected length of output)." How is that not an objective winning criterion?