File::Temp(3perl)
π File::Temp β the File::Temp manual page (perl programmers reference guide core) π
okay bestie, sit down, grab a strawberry, because we're about to talk about temporary files and honestly? this module ate. it's version 0.2312 and it's giving "safe, temporary, iconic." β¨
πΈ NAME πΈ
File::Temp β return name and handle of a temporary file safely π
β¨ VERSION β¨
version 0.2312
π¦ SYNOPSIS π¦
okay so first, the classic function interface:
use File::Temp qw/ tempfile tempdir /;
$fh = tempfile();
($fh, $filename) = tempfile();
($fh, $filename) = tempfile( $template, DIR => $dir);
($fh, $filename) = tempfile( $template, SUFFIX => '.dat');
($fh, $filename) = tempfile( $template, TMPDIR => 1 );
binmode( $fh, ":utf8" );
$dir = tempdir( CLEANUP => 1 );
($fh, $filename) = tempfile( DIR => $dir );
Object interface (the main character energy one):
require File::Temp;
use File::Temp ();
use File::Temp qw/ :seekable /;
$fh = File::Temp->new();
$fname = $fh->filename;
$fh = File::Temp->new(TEMPLATE => $template);
$fname = $fh->filename;
$tmp = File::Temp->new( UNLINK => 0, SUFFIX => '.dat' );
print $tmp "Some data\n";
print "Filename is $tmp\n";
$tmp->seek( 0, SEEK_END );
$dir = File::Temp->newdir(); # CLEANUP => 1 by default
and now the legacy stuff. the following interfaces are provided for compatibility with existing APIs β they should not be used in new code, periodt. π
MkTemp family, my beloved old-school crew:
use File::Temp qw/ :mktemp /;
($fh, $file) = mkstemp( "tmpfileXXXXX" );
($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix);
$tmpdir = mkdtemp( $template );
$unopened_file = mktemp( $template );
POSIX functions, for when you're feeling retro:
use File::Temp qw/ :POSIX /;
$file = tmpnam();
$fh = tmpfile();
($fh, $file) = tmpnam();
Compatibility functions, the ancient relics:
$unopened_file = File::Temp::tempnam( $dir, $pfx );
π DESCRIPTION π
okay so "File::Temp" can be used to create and open temporary files in a safe way. there's both a function interface and an object-oriented interface, because this module contains multitudes π
. the File::Temp constructor or the tempfile() function can be used to return the name and the open filehandle of a temporary file, and the tempdir() function can be used to create a temporary directory. it's giving "i do it all."
the security aspect of temporary file creation is emphasized such that a filehandle and filename are returned together β yes, as a little matched set, bestie π«Ά. this helps guarantee that a race condition can not occur where the temporary file is created by another process between checking for the existence of the file and its opening. honestly so real of it. additional security levels are provided to check, for example, that the sticky bit is set on world writable directories. see "safe_level" for more information. iykyk.
for compatibility with popular C library functions, Perl implementations of the mkstemp() family of functions are provided. these are mkstemp(), mkstemps(), mkdtemp() and mktemp() β four little icons π.
additionally, implementations of the standard POSIX tmpnam() and tmpfile() functions are provided if required.
β οΈ implementations ofmktemp(),tmpnam(), andtempnam()are provided, but should be used with caution since they return only a filename that was valid when function was called, so cannot guarantee that the file will not exist by the time the caller opens the filename. that's the whole vibe: filename was valid then, no promises now. π
filehandles returned by these functions support the seekable methods. slay π₯
π OBJECT-ORIENTED INTERFACE π
this is the primary interface for interacting with "File::Temp". using the OO interface a temporary file can be created when the object is constructed and the file can be removed when the object is no longer required. set it up, forget it, and it cleans up after itself. self-care π.
note that there is no method to obtain the filehandle from the "File::Temp" object. the object itself acts as a filehandle. wait, the object is the moment. the object isa "IO::Handle" and isa "IO::Seekable" so all those methods are available to you.
also, the object is configured such that it stringifies to the name of the temporary file and so can be compared to a filename directly. it numifies to the "refaddr" the same as other handles and so can be compared to other handles with "==".
$fh eq $filename # as a string
$fh != \*STDOUT # as a number
available since 0.14.
π new π
create a temporary file object.
my $tmp = File::Temp->new();
by default the object is constructed as if "tempfile" was called without options, but with the additional behaviour that the temporary file is removed by the object destructor if UNLINK is set to true (the default).
supported arguments are the same as for "tempfile": UNLINK (defaulting to true), DIR, EXLOCK, PERMS and SUFFIX. additionally, the filename template is specified using the TEMPLATE option. the OPEN option is not supported (the file is always opened). no cap.
$tmp = File::Temp->new( TEMPLATE => 'tempXXXXX',
DIR => 'mydir',
SUFFIX => '.dat');
arguments are case insensitive π«Ά.
can call croak() if an error occurs.
available since 0.14.
TEMPLATE available since 0.23.
π newdir π
create a temporary directory using an object oriented interface.
$dir = File::Temp->newdir();
by default the directory is deleted when the object goes out of scope. it's a ghost, it's gone, it never existed π.
supports the same options as the "tempdir" function. note that directories created with this method default to CLEANUP => 1.
$dir = File::Temp->newdir( $template, %options );
a template may be specified either with a leading template or with a TEMPLATE argument.
available since 0.19.
TEMPLATE available since 0.23.
π filename π
return the name of the temporary file associated with this object (if the object was created using the "new" constructor).
$filename = $tmp->filename;
this method is called automatically when the object is used as a string.
current API available since 0.14.
π dirname π
return the name of the temporary directory associated with this object (if the object was created using the "newdir" constructor).
$dirname = $tmpdir->dirname;
this method is called automatically when the object is used in string context.
π unlink_on_destroy π
control whether the file is unlinked when the object goes out of scope. the file is removed if this value is true and $KEEP_ALL is not.
$fh->unlink_on_destroy( 1 );
default is for the file to be removed.
current API available since 0.15.
π DESTROY π
when the object goes out of scope, the destructor is called. this destructor will attempt to unlink the file (using unlink1) if the constructor was called with UNLINK set to 1 (the default state if UNLINK is not specified).
no error is given if the unlink fails. it's fine. it's fine. it's fine. π
if the object has been passed to a child process during a fork, the file will be deleted when the object goes out of scope in the parent.
for a temporary directory object the directory will be removed unless the CLEANUP argument was used in the constructor (and set to false) or "unlink_on_destroy" was modified after creation.
β οΈ note that if a temp directory is your current directory, it cannot be removed β a warning will be given in this case. chdir() out of the directory before letting the object go out of scope. learn from my mistakes bestie π
if the global variable $KEEP_ALL is true, the file or directory will not be removed.
okay that's part 1 done, and there's more coming so stay seated, we're not going anywhere π
β¨ FUNCTIONS β¨
Okay bestie, this is the part you actually came for π β this whole section is about the recommended way to make temporary files and directories. Like, the ones the module wants you to use. Pay attention, no cap.
πΈ tempfile πΈ
This is the basic function for generating temporary files. The way it behaves is fully up to the options you hand it, so let's go through them one by one, mwah π
$fh = tempfile();
($fh, $filename) = tempfile();
This creates a temporary file inside the directory that's set aside for temporary files β specifically, whatever the tmpdir() function in File::Spec says it is. Simple. Iconic. π
($fh, $filename) = tempfile($template);
Now you're making a temp file in the current directory using the template you gave it. Here's the tea: any X characters hanging off the end get swapped out for random letters to build the filename. And fr fr, you need at least four X characters sitting at the end of that template or it's not gonna fly. π
($fh, $filename) = tempfile($template, SUFFIX => $suffix)
Same energy as the one above, except a suffix gets tacked onto the template after the X translation happens. Super useful when some other app needs your temp file to have a particular extension, iykyk. But heads up β go read the WARNING at the end, bestie, don't skip it π
($fh, $filename) = tempfile($template, DIR => $dir);
Translates the template just like before, except now you get to specify the directory name explicitly. Chef's kiss π©βπ³π
($fh, $filename) = tempfile($template, TMPDIR => 1);
This is literally the same as setting DIR to "File::Spec->tmpdir" β it writes the file into the same temporary directory you'd get if you hadn't passed a template at all. Shortcut queen π
($fh, $filename) = tempfile($template, UNLINK => 1);
Returns the filename and filehandle like before, but this time the file is automatically removed when the program exits β and yes, that depends on $KEEP_ALL, we'll get there.
Here's the default behavior, listen up π’: the file is removed if you asked for a file handle, and it's kept if you asked for the filename. And in scalar context (where no filename comes back at all) the file is always deleted β either on exit or when it's closed, depending on your operating system, and that's unless $KEEP_ALL is true at the moment the temp file is created.
Okay so if you need genuinely fine-grained control over exactly when a file gets yeeted, use the object-oriented interface instead. That's what it's there for. π¦
If you don't specify a template at all, one is always generated automatically for you. This auto temp file goes into tmpdir() from File::Spec, unless you explicitly pass a directory with the DIR option.
$fh = tempfile( DIR => $dir );
Now, if you call this in scalar context, only the filehandle comes back β and the file will automatically be deleted when it's closed, on operating systems that support that (go read the tmpfile() description elsewhere in this doc if you want the full lore). And honestly? This is the preferred mode of operation, because if all you've got is a filehandle, you can never accidentally create a race condition by fumbling around with the filename. Periodt. π
But β on systems that can't unlink an open file, or can't mark a file as temporary when it's opened (for example, Windows NT uses the "O_TEMPORARY" flag, cute), the file gets marked for deletion when the program ends instead. That's equivalent to setting UNLINK to 1. And in that case the "UNLINK" flag is just ignored if you pass it. Rude, but okay. π
(undef, $filename) = tempfile($template, OPEN => 0);
This one returns the filename based on the template but does not open the file. Cannot be used together with UNLINK set to true, so don't even try it bestie. The default is to always open the file, specifically to protect you from possible race conditions. A warning gets issued if warnings are turned on, so π. If you don't actually need the file opened, maybe go look at the tmpnam() and mktemp() functions described elsewhere in this document instead.
Want to open the temporary filehandle with O_EXLOCK (that's open with an exclusive file lock)? Then use "EXLOCK=>1". Big caveat though: this is only supported by some operating systems β most notably the BSD-derived ones. By default EXLOCK is false. But plot twist: former File::Temp versions set EXLOCK to true, so if you want to be sure you get an unlocked filehandle even with older versions, set "EXLOCK=>0" explicitly. Trust. π«Ά
($fh, $filename) = tempfile($template, EXLOCK => 1);
By default the temp file is created with 0600 file permissions. Use "PERMS" to change that:
($fh, $filename) = tempfile($template, PERMS => 0666);
And yes, options can be combined however you need them. Mix and match, it's your world π
Will croak() if there's an error. π₯
Version lore, because y'all love a timeline:
- Available since
0.05. UNLINKflag available since0.10.TMPDIRflag available since0.19.EXLOCKflag available since0.19.PERMSflag available since0.2310.
πΌ tempdir πΌ
This is the recommended interface for creating temporary directories. But here's the thing, bestie β by default, the directory will not be removed on exit. So technically it's not even temporary? π Yeah. That behavior can't be changed because of backwards-compatibility issues, so it is what it is.
If you do want removal, you've got two options:
- Use the
CLEANUPoption, which triggers removal on program exit. - Consider the
"newdir"method in the object interface instead β that one lets the directory get cleaned up when the object goes out of scope. Slick. β¨
The behavior of the function depends on the arguments you pass, so let's break it down:
$tempdir = tempdir();
Creates a directory in tmpdir() (see File::Spec for the deets).
$tempdir = tempdir( $template );
Creates a directory from the template you supplied. This template works a lot like the one described for tempfile(). The X characters at the end of the template get replaced with random letters to construct the directory name. And again β at least four X characters must be in the template. Four minimum, no negotiating π
$tempdir = tempdir ( DIR => $dir );
Specifies which directory to use for the temporary directory. The temporary directory name itself gets derived from an internal template.
$tempdir = tempdir ( $template, DIR => $dir );
Prepend the supplied directory name to the template. Important: the template should not include parent directory specifications itself. And if it does, any parent directory specifications get removed from the template before the supplied directory is prepended. So don't try to be sneaky π
$tempdir = tempdir ( $template, TMPDIR => 1 );
Using the supplied template, this creates the temporary directory in a standard location for temporary files. It's equivalent to doing:
$tempdir = tempdir ( $template, DIR => File::Spec->tmpdir);
...but shorter, which is the whole point, slay. Parent directory specifications get stripped from the template itself. Also: the "TMPDIR" option is ignored if "DIR" is set explicitly. And additionally, "TMPDIR" is implied if neither a template nor a directory is supplied. It just knows. π
$tempdir = tempdir( $template, CLEANUP => 1);
Creates a temporary directory using your template, but attempts to remove it β and all the files inside it β when the program exits. And bestie, note this: an attempt will be made to remove all files from the directory, even ones that weren't created by this module. Like... otherwise why would you ask it to clean it up? π€·ββοΈ The directory removal is done with the rmtree() function from the File::Path module. And obviously, if no template is specified, the temporary directory gets created in tmpdir() and will also be removed at program exit.
Will croak() if there's an error. π₯
Current API available since 0.05.
π§ MKTEMP FUNCTIONS π§
These next ones are Perl implementations of the mktemp() family of temp-file-generation system calls. Cute little nepo babies of the C world, but they're ours now π
π· mkstemp π·
Hand it a template, and it hands you back a filehandle to the temporary file plus the name of the file.
($fh, $name) = mkstemp( $template );
In scalar context? Just the filehandle. That's it. π
The template can be any filename with some number of X's appended to it, like /tmp/temp.XXXX for example. Those trailing X's get replaced with unique alphanumeric combinations.
Will croak() if there's an error. π₯
Current API available since 0.05.
πΊ mkstemps πΊ
Just like mkstemp(), except you can supply an extra argument β a suffix to be appended to the template.
($fh, $name) = mkstemps( $template, $suffix );
For example, a template of "testXXXXXX" with a suffix of ".dat" would generate a file similar to testhGji_w.dat. See how that works? Chef's kiss π©βπ³
Returns just the filehandle alone when called in scalar context.
Will croak() if there's an error. π₯
Current API available since 0.05.
π¦ mkdtemp π¦
Creates a directory from a template. The template must end in X's, and those X's get replaced by the routine.
$tmpdir_name = mkdtemp($template);
Returns the name of the temporary directory it created.
Heads up bestie: the directory must be removed by the caller. That's on you, not the module. π
Will croak() if there's an error. π₯
Current API available since 0.05.
π mktemp π
Returns a valid temporary filename, but β and this is important β it does not guarantee that the file won't get opened by someone else in the meantime.
$unopened_file = mktemp($template);
The template is the same as the one mkstemp() requires.
Will croak() if there's an error. π₯
Current API available since 0.05.
π POSIX FUNCTIONS π
This section is all about the re-implementation of tmpnam() and tmpfile() from POSIX, built using the mkstemp() from this module. Glow-up edition β¨
Unlike the POSIX implementations, the directory used for the temporary file is not specified in a system include file ("P_tmpdir") β it simply depends on whatever tmpdir() returns from File::Spec. And on some implementations, that location can be set using the "TMPDIR" environment variable... which, fair warning, may not be secure. If that's an issue for you, just use mkstemp() and specify a template yourself. Protect your peace π
π tmpnam π
When called in scalar context, it returns the full name (path included) of a temporary file β it uses mktemp() under the hood. The only check it performs is that the file doesn't already exist, but there's no guarantee that condition keeps holding. Race conditions said hi π
$file = tmpnam();
When called in list context though, you get a filehandle to the open file and a filename. This is achieved by calling mkstemp() after constructing a suitable template.
($fh, $file) = tmpnam();
If possible, use this form, bestie β it prevents possible race conditions. It's the safe one. π«Ά
See "tmpdir" in File::Spec for info on how the temporary directory gets chosen on a particular operating system.
Will croak() if there's an error. π₯
Current API available since 0.05.
πΈ tmpfile πΈ
Returns the filehandle of a temporary file.
$fh = tmpfile();
The file is removed when the filehandle is closed or when the program exits. And nope β no access to the filename is provided. It's a mystery, and it stays a mystery π
If the temporary file can't be created, undef is returned. Also, currently this command will probably not work when the temporary directory is sitting on an NFS file system. So like, be aware. π
Will croak() if there's an error. π₯
Available since 0.05.
Returning undef if unable to create the file was added in 0.12.
β¨ ADDITIONAL FUNCTIONS β¨
okay so these are the throwback besties π they exist for backwards compatibility with the common tempfile generation C library functions.
They are not exported and must be addressed using the full package name. no shortcuts, you gotta say the whole thing.
π tempnam π
Return the name of a temporary file in the specified directory using a prefix. The file is guaranteed not to exist at the time the function was called, but such guarantees are good for one clock tick only. Always use the proper form of sysopen with O_CREAT | O_EXCL if you must open such a filename.
$filename = File::Temp::tempnam( $dir, $prefix );
Equivalent to running mktemp() with $dir/$prefixXXXXXXXX (using unix file convention as an example)
Because this function uses mktemp(), it can suffer from race conditions. πββοΈπ¨
Will croak() if there is an error.
Current API available since 0.05.
π οΈ UTILITY FUNCTIONS π οΈ
Useful functions for dealing with the filehandle and filename. literally the little helpers that keep things safe and tidy β¨
π unlink0 π
Given an open filehandle and the associated filename, make a safe unlink. This is achieved by first checking that the filename and filehandle initially point to the same file and that the number of links to the file is 1 (all fields returned by stat() are compared). Then the filename is unlinked and the filehandle checked once again to verify that the number of links on that file is now 0. This is the closest you can come to making sure that the filename unlinked was the same as the file whose descriptor you hold.
unlink0($fh, $path)
or die "Error unlinking file $path safely";
Returns false on error but croaks() if there is a security anomaly. The filehandle is not closed since on some occasions this is not required.
On some platforms, for example Windows NT, it is not possible to unlink an open file (the file must be closed first). On those platforms, the actual unlinking is deferred until the program ends and good status is returned. A check is still performed to make sure that the filehandle and filename are pointing to the same thing (but not at the time the end block is executed since the deferred removal may not have access to the filehandle).
Additionally, on Windows NT not all the fields returned by stat() can be compared. For example, the dev and rdev fields seem to be different. Also, it seems that the size of the file returned by stat() does not always agree, with stat(FH) being more accurate than stat(filename), presumably because of caching issues even when using autoflush (this is usually overcome by waiting a while after writing to the tempfile before attempting to unlink0 it).
Finally, on NFS file systems the link count of the file handle does not always go to zero immediately after unlinking. Currently, this command is expected to fail on NFS disks. π
This function is disabled if the global variable $KEEP_ALL is true and an unlink on open file is supported. If the unlink is to be deferred to the END block, the file is still registered for removal.
This function should not be called if you are using the object oriented interface since it will interfere with the object destructor deleting the file.
Available Since 0.05.
If can not unlink open file, defer removal until later available since 0.06.
π§ cmpstat π§
Compare stat of filehandle with stat of provided filename. This can be used to check that the filename and filehandle initially point to the same file and that the number of links to the file is 1 (all fields returned by stat() are compared).
cmpstat($fh, $path)
or die "Error comparing handle with file";
Returns false if the stat information differs or if the link count is greater than 1. Calls croak if there is a security anomaly.
On certain platforms, for example Windows, not all the fields returned by stat() can be compared. For example, the dev and rdev fields seem to be different in Windows. Also, it seems that the size of the file returned by stat() does not always agree, with stat(FH) being more accurate than stat(filename), presumably because of caching issues even when using autoflush (this is usually overcome by waiting a while after writing to the tempfile before attempting to unlink0 it).
Not exported by default.
Current API available since 0.14.
π unlink1 π
Similar to unlink0 except after file comparison using cmpstat, the filehandle is closed prior to attempting to unlink the file. This allows the file to be removed without using an END block, but does mean that the post-unlink comparison of the filehandle state provided by unlink0 is not available.
unlink1($fh, $path)
or die "Error closing and unlinking file";
Usually called from the object destructor when using the OO interface.
Not exported by default.
This function is disabled if the global variable $KEEP_ALL is true.
Can call croak() if there is a security anomaly during the stat() comparison.
Current API available since 0.14.
π§Ή cleanup π§Ή
Calling this function will cause any temp files or temp directories that are registered for removal to be removed. This happens automatically when the process exits but can be triggered manually if the caller is sure that none of the temp files are required. This method can be registered as an Apache callback.
Note that if a temp directory is your current directory, it cannot be removed.chdir()out of the directory first before callingcleanup(). (For the cleanup at program exit when the CLEANUP flag is set, this happens automatically.)
On OSes where temp files are automatically removed when the temp file is closed, calling this function will have no effect other than to remove temporary directories (which may include temporary files).
File::Temp::cleanup();
Not exported by default.
Current API available since 0.15.
π PACKAGE VARIABLES π
These functions control the global state of the package. global vibes only π
π‘οΈ safe_level π‘οΈ
Controls the lengths to which the module will go to check the safety of the temporary file or directory before proceeding. Options are:
π STANDARD π
Do the basic security measures to ensure the directory exists and is writable, that temporary files are opened only if they do not already exist, and that possible race conditions are avoided. Finally the unlink0 function is used to remove files safely.
πΈ MEDIUM πΈ
In addition to the STANDARD security, the output directory is checked to make sure that it is owned either by root or the user running the program. If the directory is writable by group or by other, it is then checked to make sure that the sticky bit is set.
Will not work on platforms that do not support the -k test for sticky bit.
π₯ HIGH π₯
In addition to the MEDIUM security checks, also check for the possibility of ``chown() giveaway'' using the POSIX sysconf() function. If this is a possibility, each directory in the path is checked in turn for safeness, recursively walking back to the root directory.
For platforms that do not support the POSIX _PC_CHOWN_RESTRICTED symbol (for example, Windows NT) it is assumed that ``chown() giveaway'' is possible and the recursive test is performed.
The level can be changed as follows:
File::Temp->safe_level( File::Temp::HIGH );
The level constants are not exported by the module.
Currently, you must be running at least perl v5.6.0 in order to run with MEDIUM or HIGH security. This is simply because the safety tests use functions from Fcntl that are not available in older versions of perl. The problem is that the version number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though they are different versions.
On systems that do not support the HIGH or MEDIUM safety levels (for example Win NT or OS/2) any attempt to change the level will be ignored. The decision to ignore rather than raise an exception allows portable programs to be written with high security in mind for the systems that can support this without those programs failing on systems where the extra tests are irrelevant.
If you really need to see whether the change has been accepted simply examine the return value of safe_level.
$newlevel = File::Temp->safe_level( File::Temp::HIGH );
die "Could not change to high security"
if $newlevel != File::Temp::HIGH;
Available since 0.05.
π¦ TopSystemUID π¦
This is the highest UID on the current system that refers to a root UID. This is used to make sure that the temporary directory is owned by a system UID (root, bin, sys etc) rather than simply by root.
This is required since on many unix systems /tmp is not owned by root.
Default is to assume that any UID less than or equal to 10 is a root UID.
File::Temp->top_system_uid(10);
my $topid = File::Temp->top_system_uid;
This value can be adjusted to reduce security checking if required. The value is only relevant when safe_level is set to MEDIUM or higher.
Available since 0.05.
π $KEEP_ALL π
Controls whether temporary files and directories should be retained regardless of any instructions in the program to remove them automatically. This is useful for debugging but should not be used in production code.
$File::Temp::KEEP_ALL = 1;
Default is for files to be removed as requested by the caller.
In some cases, files will only be retained if this variable is true when the file is created. This means that you can not create a temporary file, set this variable and expect the temp file to still be around when the program exits.
π $DEBUG π
Controls whether debugging messages should be enabled.
$File::Temp::DEBUG = 1;
Default is for debugging mode to be disabled.
Available since 0.15.
β οΈ WARNING β οΈ
okay bestie, listen up, this is the part where we get serious π¨
For maximum security, you should always endeavor to never ever look at, touch, or even impute the existence of the filename. Like, don't even think about it, don't manifest it, don't speak it into being. Why? Because you genuinely do not know that that filename is connected to the same file as the handle you're holding!! And any attempt to "check" this can only trigger more race conditions. It's far more secure to just use the filehandle alone and dispense with the filename altogether. periodt. π
But what if you need to pass the handle to something that expects a filename? valid question, bestie. On a unix system you can use this for arbitrary programs:
"/dev/fd/" . fileno($fh)
And if it's Perl code using the 2-argument version of open, you can pass it this:
"+<=&" . fileno($fh)
Otherwise you will have to pass the filename (ugh, I know). And if that's the case, you'll have to clear the close-on-exec bit on that file descriptor before passing it off to another process:
use Fcntl qw/F_SETFD F_GETFD/;
fcntl($tmpfh, F_SETFD, 0)
or die "Can't clear close-on-exec flag on temp fh: $!\n";
Temporary files and NFS π
Some problems are associated with using temporary files that live on NFS file systems, and ngl it's recommended that a local filesystem is used whenever possible. Some of the security tests will most probably fail when the temp file isn't local π. Also, heads up: the performance of I/O operations over NFS will not be as good as for a local disk. it's giving laggy. π
Forking π΄
In some cases, files created by File::Temp get removed from within an END block. Since END blocks are triggered when a child process exits (unless POSIX::_exit() is used by the child), File::Temp takes care to only remove those temp files created by a particular process ID. Which means: a child will not attempt to remove temp files created by the parent process. slay, no friendly fire. π
Now, if you're forking many processes in parallel that are all creating temporary files, you may need to reset the random number seed using srand(EXPR) in each child β otherwise all the children will attempt to walk through the same set of random file names and may well cause themselves to give up if they exceed the number of retry attempts. like, they just clock out. π΅
Directory removal ποΈ
Note that if you have chdir'ed into the temporary directory and it is subsequently cleaned up (either in the END block or as part of object destruction), then you will get a warning from File::Path::rmtree(). so expect some yelling. π
Taint mode π§Ό
If you need to run code under taint mode, updating to the latest File::Spec is highkey recommended. On Windows, if the directory given by File::Spec::tmpdir isn't writable, File::Temp will attempt to fallback to the user's local application data directory or croak with an error. it literally cannot with unwritable directories. π
BINMODE π§¬
The file returned by File::Temp will have been opened in binary mode if such a mode is available. If that's not correct for you, use the binmode() function to change the mode of the filehandle. β¨
Also note that you can modify the encoding of a file opened by File::Temp by using binmode() too. two-for-one. π
π HISTORY π
Originally began life in May 1999 as an XS interface to the system mkstemp() function. Then in March 2000, the OpenBSD mkstemp() code was translated to Perl for total control of the code's security checking, to ensure the presence of the function regardless of operating system, and to help with portability. The module was shipped as a standard part of perl from v5.6.1. glow up complete. π
Thanks to Tom Christiansen for suggesting that this module should be written and providing ideas for code improvements and security enhancements. king behavior, fr fr π«Ά
π SEE ALSO π
"tmpnam" in POSIX,"tmpfile" in POSIX,File::Spec,File::Path
See IO::File and File::MkTemp, Apache::TempFile for different implementations of temporary file handling.
See File::Tempdir for an alternative object-oriented wrapper for the "tempdir" function. β¨
π SUPPORT π
Bugs may be submitted through the RT bug tracker at <https://rt.cpan.org/Public/Dist/Display.html?Name=File-Temp> (or to bug-File-Temp@rt.cpan.org). π
There is also a mailing list available for users of this distribution, at <http://lists.perl.org/list/cpan-workers.html>.
There is also an irc channel available for users of this distribution, at "#toolchain" on irc.perl.org β <irc://irc.perl.org/#toolchain>. come hang out bestie π¬
βοΈ AUTHOR βοΈ
Tim Jenness <tjenness@cpan.org>
π«Ά CONTRIBUTORS π«Ά
- Karen Etheridge <ether@cpan.org>
- David Golden <dagolden@cpan.org>
- Slaven Rezic <srezic@cpan.org>
- mohawk2 <mohawk2@users.noreply.github.com>
- Roy Ivy III <rivy.dev@gmail.com>
- Craig A. Berry <craigberry@mac.com>
- Olivier MenguΓ© <dolmen@cpan.org>
- Peter Rabbitson <ribasushi@cpan.org>
- Ben Tilly <btilly@gmail.com>
- Brian Mowrey <brian@drlabs.org>
- Dagfinn Ilmari MannsΓ₯ker <ilmari@ilmari.org>
- David Steinbrunner <dsteinbrunner@pobox.com>
- Ed Avis <eda@linux01.wcl.local>
- Guillem Jover <guillem@hadrons.org>
- James E. Keenan <jkeen@verizon.net>
- Kevin Ryde <user42@zip.com.au>
- mauke <lukasmai.403@gmail.com>
- Nicolas R <atoomic@cpan.org>
- Peter John Acklam <pjacklam@online.no>
- Tim Gim Yee <tim.gim.yee@gmail.com>
all icons, every single one of them ππ
βοΈ COPYRIGHT AND LICENSE βοΈ
This software is copyright (c) 2025 by Tim Jenness and the UK Particle Physics and Astronomy Research Council.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. π
and that's the whole page bestie!! πβ¨ this was perl v5.44.0, dated 2026-10-17, and it's the File::Temp(3perl) manual β go make some temp files safely, ily, mwah π«Άπ
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms