Linux.com: Working with Temporary Files under Linux (and Unix!)Dec 08, 2000, 19:55 (0 Talkback[s])
(Other stories by Elmo Recio)
"Many flavors of Linux/Unix offer a host of system calls that can be used for manipulating temporary files. Why on earth would you ever need to use special calls for manipulating temporary files? Consider that you are on a multi-user, multi-threaded OS. Hundreds, possibly thousands of processes are running at any one time. Many of these processes are forked, daemons, and/or sleeping. Now, imagine if user-a is running a process called foo. This program needs to process large amounts of data one line at a time; as it processes each line it must save it somewhere for reprocessing. Well, this is simple, just create a file in the temp volume and store the data there. No problem so far, right? What if user-b wants to run the same process for a dataset of his own? The program foo will attempt to create an identical file in the temp volume and write to it. Now the problem is obvious. The result will be two very unhappy users."
"There are several ways to work around this problem. The program can check for the existence of the file, and use an alternate filename. This method would make the program quite bulky because it's going to have to check for the existence of the second filename on the temp volume and increment to the third name if the file exists. Let's increase the number of running foo programs to 100. You can quickly see how this could create a race condition- especially if the foo program is executed at exactly the same moment. Wouldn't it be nice if the system could take care of this tedious programming? You wouldn't have to code it each time you write a new program that needs to make use of temporary files."
"Here comes Linux/Unix to save the day. Sometimes you need a file to store temporary data. Data that (in any case) only needs to be alive long enough to be used by the process, and be deleted later. Here is where the following system functions come in handy: tmpnam(), mkstemp(), tmpfile(), tempnam(), and as a result, unlink()."