Kernel#syscall

syscall(number, *args) -> integer or nil
Returns: Integer or nil · Updated March 13, 2026 · Kernel Methods
system low-level kernel syscall

The syscall method provides direct access to the operating system kernel through system call numbers. It’s extremely low-level and rarely needed in normal Ruby development.

How It Works

Each operating system has numbered system calls (like read, write, fork, etc.). The syscall method invokes these directly by number, bypassing Ruby’s normal IO abstractions.

Common System Calls (Linux x86_64)

# These numbers vary by OS and architecture!
# Linux x86_64 examples:

# sys_read (0)
syscall(0, 0, "buffer", 100)  # Read from fd 0 (stdin)

# sys_write (1)  
syscall(1, 1, "hello\n", 6)   # Write to fd 1 (stdout)

# sys_exit (60)
syscall(60, 0)                # Exit with code 0

# sys_getpid (20)
syscall(20)                   # Get process ID

Practical (But Rare) Examples

Direct Kernel Access

# Get current time via gettimeofday (requires C struct packing)
# This is extremely platform-specific

# Get current process ID
pid = syscall(20)  # __NR_getpid on Linux x86_64

Low-Level File Operations

# Direct read system call
buffer = " " * 100
bytes_read = syscall(0, 0, buffer, 100)  # read(0, buffer, 100)
puts buffer[0, bytes_read] if bytes_read > 0

Important Caveats

Platform Dependence

# System call numbers DIFFER between:
# - Linux vs BSD vs macOS
# - x86 vs ARM
# - 32-bit vs 64-bit

# NEVER hardcode syscall numbers in portable code!

Better Alternatives

# Instead of syscall, use:
File.read("file.txt")           # Instead of sys_read
$stdout.write("hi")            # Instead of sys_write
Process.pid                     # Instead of sys_getpid
Dir.entries(".")               # Instead of sys_getdents

Security Concerns

# syscalls operate at kernel level
# Wrong arguments can cause:
# - Segmentation faults
# - Kernel panics (rare)
# - Undefined behavior

# Never use syscall with untrusted input!

When You Might Use It

  • Implementing system call wrappers
  • Writing low-level systems software
  • Performance-critical code (marginal benefit)
  • Interfacing with custom kernel modules

Example: Exit

# Exit system call
syscall(60, 0)  # Same as exit(0)

# Exit with error
syscall(60, 1)  # Same as exit(1)

Warning: This method is advanced and rarely needed. Prefer Ruby’s built-in methods for any practical use case.

See Also