3

I haven't found any info about handling temporary files in Nix derivations.

I found $TMP and $TMPDIR env vars, but they both point just to /tmp, which is system global.

{
  pkgs ? import <nixpkgs> {}
}:
  pkgs.stdenv.mkDerivation {
    pname = "show-tmp"
    version = "0.1.0";
    src = ./.;
    configurePhase = ''
      echo "tmp = $tmp; TMP =  $TMP; TMPDIR = $TMPDIR"
    '';
    buildPhase = '':'';
    installPhase = '':'';        
  }

Variable $tmp is not defined inside mkDerivation. I would expect such thing, because other derivation scope vars follow low case style such as $out.

The problem with /tmp is obvious - it is global directory. I need to worry about collisions and cleaning.

My derivation-hook archives a big folder tree.

Daniil Iaitskov
  • 5,525
  • 8
  • 39
  • 49
  • 1
    Typically, anything written to `/tmp` is going to use something like `mktemp`, which is going to handle creating unique file names for you. You aren't just creating `$TMP/foo` and hoping for the best. – chepner May 19 '21 at 15:45
  • `/tmp` _was_ global 20 years ago, when Linux didn't support filesystem namespaces. It's only global today if you and your distro are sloppy about defensive configuration. – Charles Duffy Oct 05 '22 at 15:27

1 Answers1

3

If you're on Linux, don't worry. The Nix sandbox will give your build its own empty /tmp. It is removed when your derivation is done.

On macOS, $TMP and $TMPDIR are taken care of but /tmp is a potential problem.

How Nix creates a private /tmp on Linux


macOS Darwin, where Nix was installed in early 2020:

nix-build --expr 'with import <nixpkgs> {}; runCommand "hi" {} "echo a > /tmp/a; ls -al /tmp; sleep 1;"'
ls -al /private/tmp/
...
-rw-r--r--  1 nixbld1  wheel    2 May 19 12:49 a
...
Robert Hensing
  • 6,708
  • 18
  • 23