[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D27CBFGJVBGM9C503P96KX":3,"skill-same:01M6D27CBFGJVBGM9C503P96KX":73},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":49,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M6D27CBFGJVBGM9C503P96KX","systems-os",null,"Working with the operating system: files and buffered IO, fsync and durable writes, atomic replace by rename, file locking, processes and exit codes, signals and graceful shutdown, pipes and stdio, environment and permissions, paths and encodings across platforms, monotonic versus wall-clock time, sockets with timeouts, resource limits, and command-line tool conventions. Read before writing code that touches files, processes, signals or the terminal.","enowdev\u002Fenowxcli","enowdev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F179420349?v=4","01M6D1MVX2KC0X3Z9NESE7P22K","Enow Dev.","01M6D1MW1FMZGBDKWAJY4GQX81",67,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fsystems-os\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"systems os","shutdown","sockets","signals","across","conventions","time","rename","exit","files","writing","environment","read","command","tool","system","file","permissions","code","terminal","2026-11-10 10:12:30",false,"---\nname: systems-os\ndescription: \"Working with the operating system: files and buffered IO, fsync and durable writes, atomic replace by rename, file locking, processes and exit codes, signals and graceful shutdown, pipes and stdio, environment and permissions, paths and encodings across platforms, monotonic versus wall-clock time, sockets with timeouts, resource limits, and command-line tool conventions. Read before writing code that touches files, processes, signals or the terminal.\"\n---\n\n# Working with the operating system\n\nDefault OS code works on the developer's laptop: `fs::write` straight over\nthe config (a crash leaves half a file), `sh -c` with a formatted string,\na child's stdout read to the end before its stderr (a deadlock once 64 KiB\nof errors pile up), no SIGTERM handler (the container is killed after 10\nseconds with work lost), colour codes written into a pipe, `SystemTime`\nused to time a request, and `\u002F` glued into paths by hand. This skill is\nhow files, processes, signals, the terminal, time and sockets really\nbehave, and the conventions a command-line tool follows.\n\n## 1. Files and buffered IO\n\n- Each unbuffered `read` or `write` is a syscall: wrap files and sockets\n  in `BufReader`\u002F`BufWriter` (8 KiB default; 64 KiB or more for large\n  sequential files via `with_capacity`).\n- Stream large files (`lines()`, `read_until`, chunks); read a whole file\n  only when it is small and bounded (check `metadata()?.len()` first).\n- `BufWriter` flushes on drop and discards the error: `flush()?` before\n  reporting success. In C, check `fclose` and `close` (delayed errors).\n- `read` and `write` may move fewer bytes than asked: `read_exact` and\n  `write_all` loop; in C, loop and retry on `EINTR`.\n\n## 2. Durable writes\n\n- A successful `write` only reached the page cache. `sync_all()` (fsync)\n  or `sync_data()` (fdatasync) before telling anyone the data is saved; a\n  created or renamed file also needs its directory fsynced, or the entry\n  may vanish after a crash (POSIX; not on Windows).\n- macOS `fsync` does not flush the drive's cache: Rust's `sync_all` and\n  `sync_data` use `F_FULLFSYNC` there; in C call `fcntl(fd, F_FULLFSYNC)`.\n- A failed fsync is not retryable (Linux may already have marked the pages\n  clean): treat it as fatal for that file and rewrite from a good state.\n- fsync costs milliseconds: sync per batch or interval, and write down\n  what a crash may lose.\n\n## 3. Atomic replace\n\nReaders see the old file or the new one, never half of either:\n\n```rust\nuse std::io::Write;\nuse std::path::Path;\n\npub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result\u003C()> {\n    let dir = match path.parent() {\n        Some(p) if !p.as_os_str().is_empty() => p,\n        _ => Path::new(\".\"),\n    };\n    let mut tmp = tempfile::NamedTempFile::new_in(dir)?; \u002F\u002F same file system as `path`\n    tmp.write_all(bytes)?;\n    tmp.as_file().sync_all()?;\n    tmp.persist(path)?; \u002F\u002F rename(2) over the old file\n    #[cfg(unix)]\n    std::fs::File::open(dir)?.sync_all()?; \u002F\u002F make the rename itself durable\n    Ok(())\n}\n```\n\n- The temp file lives in the target's directory: `rename` across file\n  systems fails with `EXDEV`, so never `\u002Ftmp`.\n- In C: `open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644)`, write\n  all, `fsync`, `close`, `rename(tmp, path)`, then fsync the directory.\n- `NamedTempFile` is created 0600: copy the old file's mode first when it\n  matters. On Windows, replacing a file another process holds open fails:\n  retry briefly. Clean up leftover temp files (known prefix) at startup.\n\n## 4. File locks\n\n- `File::lock`, `lock_shared` and `try_lock` (std since Rust 1.89) are\n  `flock` on Unix and `LockFileEx` on Windows; open the file for writing.\n- Unix locks are advisory (they stop only processes that also lock);\n  Windows locks are mandatory. POSIX `fcntl` locks vanish when the process\n  closes any descriptor of the file; avoid them for whole-file locking.\n- Lock a `.lock` file and keep the handle for the process's life: the OS\n  releases it on exit or crash, while a file's mere existence goes stale.\n  Locks over NFS or SMB are unreliable: keep lock files on local disk.\n\n```rust\nlet lock = OpenOptions::new().create(true).truncate(false).write(true).open(dir.join(\"app.lock\"))?;\nmatch lock.try_lock() {\n    Ok(()) => {} \u002F\u002F keep `lock` alive until exit\n    Err(std::fs::TryLockError::WouldBlock) => anyhow::bail!(\"another instance is running\"),\n    Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),\n}\n```\n\n## 5. Processes\n\n- An argument array, never a shell string:\n  `Command::new(\"git\").args([\"log\", \"--format=%H\", \"--\"]).arg(&path)`.\n  User input in `sh -c` is command injection, and a value starting with\n  `-` becomes an option: put `--` before operands. `env_clear()` plus the\n  variables needed when a child must not inherit secrets.\n- `output()` reads stdout and stderr concurrently. Streaming with\n  `spawn()`, drain both pipes at once (a thread each, or async): reading\n  one to the end while the other fills its 64 KiB buffer hangs both sides.\n- Always `wait()`, or the child stays a zombie; on timeout `kill()` then\n  `wait()` (tokio: `kill_on_drop(true)` with `tokio::time::timeout`).\n- `code()` is `None` when a signal killed the child (`ExitStatusExt::signal()`\n  on Unix). A failure names the command, the code and the tail of stderr.\n\n| Exit code | Meaning |\n|---|---|\n| 0 | success |\n| 1 | general failure |\n| 2 | usage error (bad flags or arguments) |\n| 126, 127 | found but not executable; not found (shell) |\n| 128 + N | killed by signal N: 130 SIGINT, 137 SIGKILL (often the OOM killer), 143 SIGTERM |\n\n## 6. Signals and graceful shutdown\n\n| Signal | Sent by | Do |\n|---|---|---|\n| SIGINT | Ctrl-C | stop gracefully; a second one exits at once |\n| SIGTERM | `kill`, systemd, `docker stop`, Kubernetes | stop within the grace period (10s Docker, 30s Kubernetes), then SIGKILL comes |\n| SIGHUP | a closed terminal; by convention to daemons | reload configuration, or exit in interactive tools |\n| SIGPIPE | writing to a closed pipe | Rust ignores it, so writes fail with `BrokenPipe`: exit quietly |\n\n- Graceful: stop accepting work, finish or hand back in-flight work within\n  a deadline shorter than the grace period, flush buffers and logs, fsync\n  state, exit 0; past the deadline, exit non-zero. SIGKILL cannot be\n  caught, so nothing important may depend on a clean exit.\n- Handlers call only async-signal-safe functions (`write`, `_exit`, a\n  `volatile sig_atomic_t` or atomic store): no `malloc`, `printf`, locks\n  or logging. Set a flag or write to a self-pipe and act in normal code,\n  or use `signalfd` (Linux) or `sigwait` on a dedicated thread. Rust:\n  `tokio::signal`, or `signal-hook` and `ctrlc` in sync code.\n\n```rust\nasync fn shutdown_signal() {\n    let ctrl_c = async { tokio::signal::ctrl_c().await.expect(\"install Ctrl-C handler\") };\n    #[cfg(unix)]\n    let terminate = async {\n        use tokio::signal::unix::{signal, SignalKind};\n        signal(SignalKind::terminate()).expect(\"install SIGTERM handler\").recv().await;\n    };\n    #[cfg(not(unix))]\n    let terminate = std::future::pending::\u003C()>();\n    tokio::select! { () = ctrl_c => {}, () = terminate => {} }\n}\n```\n\nPID 1 in a container has no default signal actions: unhandled SIGTERM is\nignored until SIGKILL. Handle it, or run under `tini` (`docker run --init`).\n\n## 7. stdio and the terminal\n\n- stdout carries the output a pipe or script consumes; logs, progress,\n  warnings and errors go to stderr. `--json` gives machine-readable output\n  with a stable shape.\n- Rust's stdout is line-buffered even into a pipe: for bulk output use\n  `BufWriter::new(io::stdout().lock())` and flush at the end.\n- `std::io::IsTerminal` (`isatty` in C) gates colours, progress bars and\n  prompts. Honour `NO_COLOR` (set and non-empty: no colour),\n  `--color=auto|always|never` and `TERM=dumb`. `-` as a file argument\n  means stdin or stdout.\n- `app | head` closes the pipe early: `println!` panics on it, so bulk\n  writers use `writeln!`, treat `ErrorKind::BrokenPipe` as the end, and\n  exit 0.\n\n## 8. Environment and permissions\n\n- Read environment variables once at startup into a typed config,\n  validate, fail fast naming the variable; never print a secret's value or\n  log the environment. `env::var` fails on non-UTF-8: `var_os` for paths.\n- Precedence: flags over environment over config file over defaults; a\n  `config show` command (secrets masked) saves hours.\n- `std::env::set_var` is `unsafe` in edition 2024 (other threads may read\n  the environment): pass a child its variables with `Command::env`.\n- Files get the requested mode minus the umask (usually 022). Secrets:\n  `0o600` files in a `0o700` directory, set at creation\n  (`OpenOptionsExt::mode(0o600)`), not by `chmod` afterwards. Nothing\n  world-writable; refuse a secrets file others can read, as ssh does.\n- In shared directories create with `create_new(true)` (`O_EXCL`) so a\n  planted symlink cannot redirect the write. Rust opens descriptors\n  close-on-exec; in C pass `O_CLOEXEC` and `SOCK_CLOEXEC`.\n\n## 9. Paths and encodings\n\n- Paths are OS strings, not text: `PathBuf` and `OsString` (Unix paths are\n  bytes, Windows paths possibly ill-formed UTF-16), `std::filesystem::path`\n  in C++. Show with `display()`; `to_str()` only where UTF-8 is required.\n- Build with `join`, never `format!(\"{dir}\u002F{name}\")`. `join` with an\n  absolute path replaces the base (`Path::new(\"\u002Fsrv\").join(\"\u002Fetc\u002Fpasswd\")`\n  is `\u002Fetc\u002Fpasswd`): reject absolute user-supplied names and `..`\n  components (`Component::ParentDir`) first.\n- Windows: `\\` separators, drive letters, `\\\\?\\` and UNC prefixes, a\n  260-character limit unless long paths are enabled, reserved names\n  (`CON`, `NUL`, `COM1`). macOS and Windows are case-insensitive by\n  default: `README.md` and `readme.md` are one file there.\n- `fs::canonicalize` resolves symlinks but returns `\\\\?\\C:\\` paths on\n  Windows that other tools reject: `dunce::canonicalize`. Check\n  containment after canonicalising, and open once rather than check then\n  open (TOCTOU).\n- Temporary files through `tempfile` (deleted on drop), never a fixed name\n  in `\u002Ftmp`; config and data in the platform's directories (`directories`).\n\n## 10. Time\n\n- Durations, timeouts, rate limits and retries use the monotonic clock\n  (`Instant`, `CLOCK_MONOTONIC`, `steady_clock`), which never jumps back.\n  Timestamps use the wall clock (`SystemTime`), stored in UTC and zoned\n  only for display (`jiff` or `chrono`); NTP and people move it.\n- Compute a deadline once (`let deadline = Instant::now() + timeout;`) and\n  give each wait the remaining time, so retries cannot stretch it.\n\n## 11. Sockets\n\n- Every connect, read and write has a timeout: resolve with\n  `to_socket_addrs()`, then `TcpStream::connect_timeout(&addr,\n  Duration::from_secs(5))` per address, `set_read_timeout`,\n  `set_write_timeout`; in async code `tokio::time::timeout` on each step.\n- `set_nodelay(true)` for request-response protocols (Nagle plus delayed\n  ACKs add 40 to 200ms); leave it off for bulk streams.\n- std's `TcpListener::bind` sets `SO_REUSEADDR` on Unix and a backlog of\n  128; `socket2` for `SO_REUSEPORT`, keepalive and buffer sizes.\n- A read of 0 bytes is end of stream; a reset is an error. Frame the\n  protocol (`systems-formats`, section 7).\n\n## 12. Resource limits\n\n- Open files: the soft limit is often 1024 on Linux and 256 by default on\n  macOS. Servers raise it to the hard limit at startup\n  (`setrlimit(RLIMIT_NOFILE)`) or set `LimitNOFILE=` in the systemd unit.\n- `EMFILE` under steady load is usually a descriptor leak: watch\n  `ls \u002Fproc\u002F\u003Cpid>\u002Ffd | wc -l` or `lsof -p \u003Cpid>` over time. Other limits\n  that bite: `ulimit -s`, processes per user, inotify watches.\n\n## 13. Command-line conventions\n\n- `--help`\u002F`-h`, `--version`\u002F`-V`, subcommands for distinct actions, `--`\n  to end options, kebab-case long flags, `-q` and repeatable `-v`.\n- Errors to stderr as `mytool: cannot read config.toml: permission\n  denied`, with a hint when there is one; exit codes as in section 5.\n- clap derive; `env = \"...\"` (feature `env`) ties a flag to a variable;\n  `clap_complete` generates shell completions:\n\n```rust\n#[derive(clap::Parser)]\n#[command(version, about)]\nstruct Cli {\n    \u002F\u002F\u002F Config file (default: the platform's config directory)\n    #[arg(long, env = \"MYTOOL_CONFIG\")]\n    config: Option\u003CPathBuf>,\n    #[arg(short, long, action = clap::ArgAction::Count)]\n    verbose: u8,\n    #[command(subcommand)]\n    command: Command,\n}\n```\n\n## Check it\n\n- Kill the process mid-write (`kill -9` in a loop in a test script): the\n  file is always the old or the new version.\n- `timeout -s TERM 5 .\u002Fapp` or `docker stop`: in-flight work finishes,\n  exit code 0, inside the deadline.\n- `.\u002Fapp | head -1` exits quietly; `.\u002Fapp > out.txt` and `NO_COLOR=1 .\u002Fapp`\n  print no colour codes; a path with spaces and non-ASCII works.\n- CI runs the tests on Linux, macOS and Windows (paths, line endings,\n  permissions and signals differ); say which could not be tested here.\n\n## Avoid\n\nWriting over a file in place; a temp file on another file system; no\ndirectory fsync; retrying a failed fsync; lock files without a lock; shell\nstrings for commands; one pipe drained before the other; unwaited\nchildren; no SIGTERM handling; work inside signal handlers; logs on\nstdout; colour into pipes; `set_var` at run time; paths as `String` or\nglued with `\u002F`; wall-clock time for durations; sockets without timeouts;\nsecrets in logs or world-readable files.\n","# Working with the operating system\n\nDefault OS code works on the developer's laptop: `fs::write` straight over\nthe config (a crash leaves half a file), `sh -c` with a formatted string,\na child's stdout read to the end before its stderr (a deadlock once 64 KiB\nof errors pile up), no SIGTERM handler (the container is killed after 10\nseconds with work lost), colour codes written into a pipe, `SystemTime`\nused to time a request, and `\u002F` glued into paths by hand. This skill is\nhow files, processes, signals, the terminal, time and sockets really\nbehave, and the conventions a command-line tool follows.\n\n## 1. Files and buffered IO\n\n- Each unbuffered `read` or `write` is a syscall: wrap files and sockets\n  in `BufReader`\u002F`BufWriter` (8 KiB default; 64 KiB or more for large\n  sequential files via `with_capacity`).\n- Stream large files (`lines()`, `read_until`, chunks); read a whole file\n  only when it is small and bounded (check `metadata()?.len()` first).\n- `BufWriter` flushes on drop and discards the error: `flush()?` before\n  reporting success. In C, check `fclose` and `close` (delayed errors).\n- `read` and `write` may move fewer bytes than asked: `read_exact` and\n  `write_all` loop; in C, loop and retry on `EINTR`.\n\n## 2. Durable writes\n\n- A successful `write` only reached the page cache. `sync_all()` (fsync)\n  or `sync_data()` (fdatasync) before telling anyone the data is saved; a\n  created or renamed file also needs its directory fsynced, or the entry\n  may vanish after a crash (POSIX; not on Windows).\n- macOS `fsync` does not flush the drive's cache: Rust's `sync_all` and\n  `sync_data` use `F_FULLFSYNC` there; in C call `fcntl(fd, F_FULLFSYNC)`.\n- A failed fsync is not retryable (Linux may already have marked the pages\n  clean): treat it as fatal for that file and rewrite from a good state.\n- fsync costs milliseconds: sync per batch or interval, and write down\n  what a crash may lose.\n\n## 3. Atomic replace\n\nReaders see the old file or the new one, never half of either:\n\n```rust\nuse std::io::Write;\nuse std::path::Path;\n\npub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result\u003C()> {\n    let dir = match path.parent() {\n        Some(p) if !p.as_os_str().is_empty() => p,\n        _ => Path::new(\".\"),\n    };\n    let mut tmp = tempfile::NamedTempFile::new_in(dir)?; \u002F\u002F same file system as `path`\n    tmp.write_all(bytes)?;\n    tmp.as_file().sync_all()?;\n    tmp.persist(path)?; \u002F\u002F rename(2) over the old file\n    #[cfg(unix)]\n    std::fs::File::open(dir)?.sync_all()?; \u002F\u002F make the rename itself durable\n    Ok(())\n}\n```\n\n- The temp file lives in the target's directory: `rename` across file\n  systems fails with `EXDEV`, so never `\u002Ftmp`.\n- In C: `open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644)`, write\n  all, `fsync`, `close`, `rename(tmp, path)`, then fsync the directory.\n- `NamedTempFile` is created 0600: copy the old file's mode first when it\n  matters. On Windows, replacing a file another process holds open fails:\n  retry briefly. Clean up leftover temp files (known prefix) at startup.\n\n## 4. File locks\n\n- `File::lock`, `lock_shared` and `try_lock` (std since Rust 1.89) are\n  `flock` on Unix and `LockFileEx` on Windows; open the file for writing.\n- Unix locks are advisory (they stop only processes that also lock);\n  Windows locks are mandatory. POSIX `fcntl` locks vanish when the process\n  closes any descriptor of the file; avoid them for whole-file locking.\n- Lock a `.lock` file and keep the handle for the process's life: the OS\n  releases it on exit or crash, while a file's mere existence goes stale.\n  Locks over NFS or SMB are unreliable: keep lock files on local disk.\n\n```rust\nlet lock = OpenOptions::new().create(true).truncate(false).write(true).open(dir.join(\"app.lock\"))?;\nmatch lock.try_lock() {\n    Ok(()) => {} \u002F\u002F keep `lock` alive until exit\n    Err(std::fs::TryLockError::WouldBlock) => anyhow::bail!(\"another instance is running\"),\n    Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),\n}\n```\n\n## 5. Processes\n\n- An argument array, never a shell string:\n  `Command::new(\"git\").args([\"log\", \"--format=%H\", \"--\"]).arg(&path)`.\n  User input in `sh -c` is command injection, and a value starting with\n  `-` becomes an option: put `--` before operands. `env_clear()` plus the\n  variables needed when a child must not inherit secrets.\n- `output()` reads stdout and stderr concurrently. Streaming with\n  `spawn()`, drain both pipes at once (a thread each, or async): reading\n  one to the end while the other fills its 64 KiB buffer hangs both sides.\n- Always `wait()`, or the child stays a zombie; on timeout `kill()` then\n  `wait()` (tokio: `kill_on_drop(true)` with `tokio::time::timeout`).\n- `code()` is `None` when a signal killed the child (`ExitStatusExt::signal()`\n  on Unix). A failure names the command, the code and the tail of stderr.\n\n| Exit code | Meaning |\n|---|---|\n| 0 | success |\n| 1 | general failure |\n| 2 | usage error (bad flags or arguments) |\n| 126, 127 | found but not executable; not found (shell) |\n| 128 + N | killed by signal N: 130 SIGINT, 137 SIGKILL (often the OOM killer), 143 SIGTERM |\n\n## 6. Signals and graceful shutdown\n\n| Signal | Sent by | Do |\n|---|---|---|\n| SIGINT | Ctrl-C | stop gracefully; a second one exits at once |\n| SIGTERM | `kill`, systemd, `docker stop`, Kubernetes | stop within the grace period (10s Docker, 30s Kubernetes), then SIGKILL comes |\n| SIGHUP | a closed terminal; by convention to daemons | reload configuration, or exit in interactive tools |\n| SIGPIPE | writing to a closed pipe | Rust ignores it, so writes fail with `BrokenPipe`: exit quietly |\n\n- Graceful: stop accepting work, finish or hand back in-flight work within\n  a deadline shorter than the grace period, flush buffers and logs, fsync\n  state, exit 0; past the deadline, exit non-zero. SIGKILL cannot be\n  caught, so nothing important may depend on a clean exit.\n- Handlers call only async-signal-safe functions (`write`, `_exit`, a\n  `volatile sig_atomic_t` or atomic store): no `malloc`, `printf`, locks\n  or logging. Set a flag or write to a self-pipe and act in normal code,\n  or use `signalfd` (Linux) or `sigwait` on a dedicated thread. Rust:\n  `tokio::signal`, or `signal-hook` and `ctrlc` in sync code.\n\n```rust\nasync fn shutdown_signal() {\n    let ctrl_c = async { tokio::signal::ctrl_c().await.expect(\"install Ctrl-C handler\") };\n    #[cfg(unix)]\n    let terminate = async {\n        use tokio::signal::unix::{signal, SignalKind};\n        signal(SignalKind::terminate()).expect(\"install SIGTERM handler\").recv().await;\n    };\n    #[cfg(not(unix))]\n    let terminate = std::future::pending::\u003C()>();\n    tokio::select! { () = ctrl_c => {}, () = terminate => {} }\n}\n```\n\nPID 1 in a container has no default signal actions: unhandled SIGTERM is\nignored until SIGKILL. Handle it, or run under `tini` (`docker run --init`).\n\n## 7. stdio and the terminal\n\n- stdout carries the output a pipe or script consumes; logs, progress,\n  warnings and errors go to stderr. `--json` gives machine-readable output\n  with a stable shape.\n- Rust's stdout is line-buffered even into a pipe: for bulk output use\n  `BufWriter::new(io::stdout().lock())` and flush at the end.\n- `std::io::IsTerminal` (`isatty` in C) gates colours, progress bars and\n  prompts. Honour `NO_COLOR` (set and non-empty: no colour),\n  `--color=auto|always|never` and `TERM=dumb`. `-` as a file argument\n  means stdin or stdout.\n- `app | head` closes the pipe early: `println!` panics on it, so bulk\n  writers use `writeln!`, treat `ErrorKind::BrokenPipe` as the end, and\n  exit 0.\n\n## 8. Environment and permissions\n\n- Read environment variables once at startup into a typed config,\n  validate, fail fast naming the variable; never print a secret's value or\n  log the environment. `env::var` fails on non-UTF-8: `var_os` for paths.\n- Precedence: flags over environment over config file over defaults; a\n  `config show` command (secrets masked) saves hours.\n- `std::env::set_var` is `unsafe` in edition 2024 (other threads may read\n  the environment): pass a child its variables with `Command::env`.\n- Files get the requested mode minus the umask (usually 022). Secrets:\n  `0o600` files in a `0o700` directory, set at creation\n  (`OpenOptionsExt::mode(0o600)`), not by `chmod` afterwards. Nothing\n  world-writable; refuse a secrets file others can read, as ssh does.\n- In shared directories create with `create_new(true)` (`O_EXCL`) so a\n  planted symlink cannot redirect the write. Rust opens descriptors\n  close-on-exec; in C pass `O_CLOEXEC` and `SOCK_CLOEXEC`.\n\n## 9. Paths and encodings\n\n- Paths are OS strings, not text: `PathBuf` and `OsString` (Unix paths are\n  bytes, Windows paths possibly ill-formed UTF-16), `std::filesystem::path`\n  in C++. Show with `display()`; `to_str()` only where UTF-8 is required.\n- Build with `join`, never `format!(\"{dir}\u002F{name}\")`. `join` with an\n  absolute path replaces the base (`Path::new(\"\u002Fsrv\").join(\"\u002Fetc\u002Fpasswd\")`\n  is `\u002Fetc\u002Fpasswd`): reject absolute user-supplied names and `..`\n  components (`Component::ParentDir`) first.\n- Windows: `\\` separators, drive letters, `\\\\?\\` and UNC prefixes, a\n  260-character limit unless long paths are enabled, reserved names\n  (`CON`, `NUL`, `COM1`). macOS and Windows are case-insensitive by\n  default: `README.md` and `readme.md` are one file there.\n- `fs::canonicalize` resolves symlinks but returns `\\\\?\\C:\\` paths on\n  Windows that other tools reject: `dunce::canonicalize`. Check\n  containment after canonicalising, and open once rather than check then\n  open (TOCTOU).\n- Temporary files through `tempfile` (deleted on drop), never a fixed name\n  in `\u002Ftmp`; config and data in the platform's directories (`directories`).\n\n## 10. Time\n\n- Durations, timeouts, rate limits and retries use the monotonic clock\n  (`Instant`, `CLOCK_MONOTONIC`, `steady_clock`), which never jumps back.\n  Timestamps use the wall clock (`SystemTime`), stored in UTC and zoned\n  only for display (`jiff` or `chrono`); NTP and people move it.\n- Compute a deadline once (`let deadline = Instant::now() + timeout;`) and\n  give each wait the remaining time, so retries cannot stretch it.\n\n## 11. Sockets\n\n- Every connect, read and write has a timeout: resolve with\n  `to_socket_addrs()`, then `TcpStream::connect_timeout(&addr,\n  Duration::from_secs(5))` per address, `set_read_timeout`,\n  `set_write_timeout`; in async code `tokio::time::timeout` on each step.\n- `set_nodelay(true)` for request-response protocols (Nagle plus delayed\n  ACKs add 40 to 200ms); leave it off for bulk streams.\n- std's `TcpListener::bind` sets `SO_REUSEADDR` on Unix and a backlog of\n  128; `socket2` for `SO_REUSEPORT`, keepalive and buffer sizes.\n- A read of 0 bytes is end of stream; a reset is an error. Frame the\n  protocol (`systems-formats`, section 7).\n\n## 12. Resource limits\n\n- Open files: the soft limit is often 1024 on Linux and 256 by default on\n  macOS. Servers raise it to the hard limit at startup\n  (`setrlimit(RLIMIT_NOFILE)`) or set `LimitNOFILE=` in the systemd unit.\n- `EMFILE` under steady load is usually a descriptor leak: watch\n  `ls \u002Fproc\u002F\u003Cpid>\u002Ffd | wc -l` or `lsof -p \u003Cpid>` over time. Other limits\n  that bite: `ulimit -s`, processes per user, inotify watches.\n\n## 13. Command-line conventions\n\n- `--help`\u002F`-h`, `--version`\u002F`-V`, subcommands for distinct actions, `--`\n  to end options, kebab-case long flags, `-q` and repeatable `-v`.\n- Errors to stderr as `mytool: cannot read config.toml: permission\n  denied`, with a hint when there is one; exit codes as in section 5.\n- clap derive; `env = \"...\"` (feature `env`) ties a flag to a variable;\n  `clap_complete` generates shell completions:\n\n```rust\n#[derive(clap::Parser)]\n#[command(version, about)]\nstruct Cli {\n    \u002F\u002F\u002F Config file (default: the platform's config directory)\n    #[arg(long, env = \"MYTOOL_CONFIG\")]\n    config: Option\u003CPathBuf>,\n    #[arg(short, long, action = clap::ArgAction::Count)]\n    verbose: u8,\n    #[command(subcommand)]\n    command: Command,\n}\n```\n\n## Check it\n\n- Kill the process mid-write (`kill -9` in a loop in a test script): the\n  file is always the old or the new version.\n- `timeout -s TERM 5 .\u002Fapp` or `docker stop`: in-flight work finishes,\n  exit code 0, inside the deadline.\n- `.\u002Fapp | head -1` exits quietly; `.\u002Fapp > out.txt` and `NO_COLOR=1 .\u002Fapp`\n  print no colour codes; a path with spaces and non-ASCII works.\n- CI runs the tests on Linux, macOS and Windows (paths, line endings,\n  permissions and signals differ); say which could not be tested here.\n\n## Avoid\n\nWriting over a file in place; a temp file on another file system; no\ndirectory fsync; retrying a failed fsync; lock files without a lock; shell\nstrings for commands; one pipe drained before the other; unwaited\nchildren; no SIGTERM handling; work inside signal handlers; logs on\nstdout; colour into pipes; `set_var` at run time; paths as `String` or\nglued with `\u002F`; wall-clock time for durations; sockets without timeouts;\nsecrets in logs or world-readable files.\n",{"name":5,"description":7},"main","38293fe1b096e6bf3646c7344c38786ed688f464","crates\u002Fenowx-core\u002Fskills\u002Fsystems-os",21,"https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli","https:\u002F\u002Fenowx.ai","https:\u002F\u002Fgithub.com\u002Fenowdev","Pretending to be a Developer","2026-10-06 02:05:35",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add enowdev\u002Fenowxcli --skill systems-os",{"tool":59,"command":60},"bunx","bunx skills add enowdev\u002Fenowxcli --skill systems-os",{"tool":62,"command":63},"pnpm","pnpm dlx skills add enowdev\u002Fenowxcli --skill systems-os","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fsystems-os\u002FSKILL.md",true,[67],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"references\u002FROUTING.md","REFERENCE","参考文档",2052,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fs977043\u002Friver-review\u002Fskills\u002Fagent-skills\u002Friver-review-security\u002Freferences\u002FROUTING.md",[74,85,101,114,134,153],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":39},"01M6D2HQYSQD9N7MTNDT4A7CBM","demo-skill","Project-scope demo skill for tests.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fworkspace\u002F.agents\u002Fskills\u002Fdemo-skill\u002FSKILL.md",[],[81,82,83,84,31],"demo skill","demo","tests","project",{"skillNo":86,"name":29,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":39},"01M6D2HM0GCPM0TM2HPG9HHR2R","Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fwriting\u002FSKILL.md",[],[29,91,92,93,94,95,31,96,97,98,99,100],"text","emails","empty","drop","document","page","voice","notifications","documentation","translate",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":39},"01M6D2HG07YS49NM196Q0R3AZ8","ui","Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui\u002FSKILL.md",[],[103,108,109,110,111,96,112,31,113],"icons","components","SET","responsive","layout","before building",{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":39},"01M6D2HB59HZHWG1RYZDV4SJ91","ui-themes","Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-themes\u002FSKILL.md",[],[103,121,122,123,124,125,126,127,128,31,113,129,96,37,130,131,108,132,133],"ui themes","switching","photos","tokens","drawing","focus","maps","Art","flash","Charts","content","screenshots","logo",{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":140,"publishedAt":39},"01M6D2H5R5KRAE524C8QX0T7Q0","ui-structure","Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-structure\u002FSKILL.md",[],[141,103,142,109,143,144,37,145,146,147,112,124,148,149,150,31,113,96,151,152],"structure","ui structure","pricing","dashboard","Blueprint","article","anatomy","styling","primitives","list","why","how",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":39},"01M6D2H0ZZBJG77MBGPZHA6MWD","ui-stack-vue","Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-stack-vue\u002FSKILL.md",[],[103,160,161,162,163,164,165,166,112,84,167,168,31,169,170,171,172,173,174,175],"vue","stack","ui stack vue","forms","pages","watch","runtime","transitions","fetch","pinia","nuxt","template","server","config","directory","testing"]