Embedding Assembly
Objective: Use assembly code below to invoke getpid syscall. Obtain PID from %eax and print it to stdout.
movl $20, %eax
int $0x80
Note that this should work under most unix platforms running on x86. Alternative solution that works on x86-64 would be:
movl $39, %eax
syscall
Python
Embedding assembly makes little sense in an interpreted language like Python where typical intention is to be platform-agnostic. Hovewer, for the sake of example we can use CFFI module that will compile C code on the fly. C code in turn will embed our assembly:
from cffi import FFI
ffi = FFI()
ffi.set_source("_pidlib", r"""
int get_pid() {
    int pid;
    asm("movl $20, %%eax\n"
        "int $0x80\n"
        "movl %%eax, %0\n" : "=r"(pid));
    return pid;
}
""")
ffi.cdef("int get_pid();")
ffi.compile()
from _pidlib.lib import get_pid
print(get_pid())
Rust
Intel syntax applies.
use std::arch::asm; fn main() { let mut pid: u32; unsafe { asm!( "mov eax, $20", "int $0x80", "mov {pid:e}, eax", pid = out(reg) pid, ); } println!("{}", pid); }
Crystal
AT&T syntax applies.
fun getpid() : Int32
    pid = uninitialized Int32
    
    asm("
    movl $$20, %eax
    int $$0x80
    movl %eax, $0" : "=r"(pid))
    
    return pid
end
puts getpid