68 / Systems

Process Control

Nyx provides POSIX process builtins: getpid, getcwd, chdir, isatty, stat. These are the building blocks for command-line tools and shells.

68-process-control.nxSource →
// 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
}
Illustrative outputstdout
my pid: 1501659
cwd: /tmp/demo
stdout is not a terminal (piped)
/tmp is a directory
changed to: /tmp
back to: /tmp/demo

How it works

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 what a shell built in Nyx uses for its built-in commands.