What's a POSIX function for creating a tempora

2019-06-25 12:00发布

问题:

For the task of creating a temporary directory in /tmp, how would one choose between mkdtemp, mkstemp, etc., for portable code?

回答1:

I presume you need to create a temporary directory inside a directory where other users may have write permission.

As an administrator, you should set things up so that each user has its own TMPDIR (e.g. with pam-tmpdir — or even better with per-process namespaces, but that takes more setup). As an application writer, however, you can't assume this, so you need to cope with a world-writable /tmp.

The right function here is mkdtemp, since mkstemp can only create regular files. mkdtemp was only introduced in POSIX.1 2008, so in principle it might not be available on all POSIX platforms yet. However, it has been available on major platforms for a long time:

  • on OpenBSD since 2.2 (1997)
  • on FreeBSD since 2.2.7 (1998)
  • on NetBSD since 1.4 (1998)
  • on OSX since… 10.0?
  • on Linux (with Glibc) since Glibc 2.2 (1999)
  • in dietlibc since at least 2001
  • in uClibc since its beginning, I think
  • in MINIX 3
  • on Solaris only since Solaris 10

So in practice, you can safely go with mkdtemp. If you need a fallback, include the OpenBSD implementation in your source.