Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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: several 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top