views:

462

answers:

3

Both operations create an empty file and return the filename but mkstemp leaves the file open in exclusive mode and gives you the handle. Is there a safety benefit to the C-function? Does this imply that there is a safety hole in the command-line version?

As an aside, it is interesting that there are several related functions in the C api on Linux and most of them say "Don't use this function" (or similar) in their man page.

A: 

The most obvious difference between a system call and a command line function is that command line functions are used by people or their shell scripts, while system calls are always done by programs.

It would be quite hard to hand a person a file handle.

Regarding "safety", you should think about race conditions: serveral instances of one program call mkstemp at the same time, but each one is guaranteed to have a unique temporary file. If the program shelled out and called the command line version, it'd be almost impossible to guarantee this.

innaM
+2  A: 

As you can easily see from mktemp(1) source code, it essentially does nothing but calling mkstemp(3).

Exclusive mode in Linux means that function will fail if the file already exists, it does not guarantee locking. Other process can delete this file, create it again and fill it with data, despite the file handle being open(3) by your process.

There is no additional safety in C function compared to command line utility.

Quassnoi
mktemp(1) calls mkstemp(3), but it also closes the resulting file handle. But, as you point out, there is apparently no value in holding the open handle. It would appear that neither approach is particularly safe from malicious attacks.
+5  A: 

One trick with temporary files in Unix-like operating systems (including Linux and Mac OS) is as soon as you open the file, delete it. You can still access the file, but nobody else can see it or do anything to it, and it will go away as soon as you close the file, even if your program dies a horrible death.

Paul Tomblin
In other words, the file loses its name but not its data after unlinking until you close it.
strager
This is a great tip! I was looking at tmpfile(3) which does what you describe here, but I didn't understand how it worked until I read your post.
great idea! i suspect another usecase is for PID-files? i often see stale pidfiles after programs crashed. wouldn't the technique described by you solve that issue too?
Johannes Schaub - litb
Well, obviously you can use this technique any time you want a temporary file for your own program, and it solves the cleanup problem. But you can't use it for lock files, of course.
Paul Tomblin
Very cool. Never thought of that.
Bernard