Nyx by Example

Process Control

Nyx provides POSIX process builtins: getpid, getcwd, chdir, isatty, stat. These are the building blocks for tools like nyx-shell.

Code

// Process control — pid, working directory, environment
// Control de procesos — pid, directorio de trabajo, entorno

fn main() -> int {
    // Get current process ID
    let pid: int = getpid()
    print("my pid: " + int_to_string(pid))

    // Get current working directory
    let cwd: String = getcwd()
    print("cwd: " + cwd)

    // Check if stdout is a terminal
    let is_tty: bool = isatty(1)
    if is_tty {
        print("stdout is a terminal")
    } else {
        print("stdout is not a terminal (piped)")
    }

    // File stat
    let info: Array = stat("/tmp")
    let is_dir: int = info[3]
    if is_dir == 1 {
        print("/tmp is a directory")
    }

    // Change directory and back
    let original: String = getcwd()
    chdir("/tmp")
    print("changed to: " + getcwd())
    chdir(original)
    print("back to: " + getcwd())

    return 0
}

Output

my pid: 12345
cwd: /home/admin/NyxLang
stdout is not a terminal (piped)
/tmp is a directory
changed to: /tmp
back to: /home/admin/NyxLang

Explanation

getpid() returns the current process ID. getcwd() returns the current working directory as a string. chdir(path) changes the working directory.

isatty(fd) checks whether a file descriptor refers to a terminal. File descriptor 0 is stdin, 1 is stdout, 2 is stderr. This is useful for deciding whether to emit color codes or interactive prompts.

stat(path) returns metadata about a file or directory as [size, mode, mtime, is_dir, is_regular]. The is_dir flag (index 3) is 1 for directories, 0 otherwise. These primitives are the foundation of nyx-shell's built-in commands.

← Previous Next →

Source: examples/by-example/68-process-control.nx