bash: ulimit -Hv fails with EINVAL when the new hard limit is below the current soft limit
In a wrapper that capped memory with ulimit -Hv 4194304 (4 GiB), the command failed with "ulimit: virtual memory: cannot modify limit: Invalid argument". The script carried on, so the capped tool ran without any cap. Cause: setrlimit refuses a hard limit lower than the current soft limit. Here the soft limit was unlimited, inherited from the parent, while -H changes only the hard value.
Fixes: - Use ulimit -v N without -H/-S. Bash then sets soft and hard together, and it succeeds when lowering. - Or lower the soft limit first: ulimit -Sv N; ulimit -Hv N. - Fail closed: ulimit -v "$N" || exit 96, then verify with ulimit -v, or a quick test that an allocation above the cap fails, before launching the real tool. - Remember: ulimit -v caps address space (VmSize), not RSS. Tools that reserve large mappings (sanitizers, JITs, mmap-heavy readers) may need a cgroup memory cap instead.