diff options
author | Scott Ullrich <sullrich@pfsense.org> | 2010-02-14 14:53:43 -0500 |
---|---|---|
committer | Scott Ullrich <sullrich@pfsense.org> | 2010-02-14 14:53:43 -0500 |
commit | fcbbdd850ff28dea780e43f7c8a85c128ec50260 (patch) | |
tree | 83abee2739b35eedb8b8a3123d066371b9009686 /etc | |
parent | b7544cb01603d12b752200582972d566df497bb2 (diff) | |
download | pfsense-fcbbdd850ff28dea780e43f7c8a85c128ec50260.zip pfsense-fcbbdd850ff28dea780e43f7c8a85c128ec50260.tar.gz |
Adding from RELENG_1_2: safe_write_file() Writes a file out atomically by first writing to a temporary file of the same name but ending with the pid of the current process, them renaming the temporary file over the original.
Diffstat (limited to 'etc')
-rw-r--r-- | etc/inc/pfsense-utils.inc | 41 |
1 files changed, 40 insertions, 1 deletions
diff --git a/etc/inc/pfsense-utils.inc b/etc/inc/pfsense-utils.inc index 989396b..521d07e 100644 --- a/etc/inc/pfsense-utils.inc +++ b/etc/inc/pfsense-utils.inc @@ -1713,4 +1713,43 @@ function update_alias_names_upon_change($section, $subsection, $fielda, $fieldb, } -?> +/****f* pfsense-utils/safe_write_file + * NAME + * safe_write_file - Write a file out atomically + * DESCRIPTION + * safe_write_file() Writes a file out atomically by first writing to a + * temporary file of the same name but ending with the pid of the current + * process, them renaming the temporary file over the original. + * INPUTS + * $filename - string containing the filename of the file to write + * $content - string containing the file content to write to file + * $force_binary - boolean denoting whether we should force binary + * mode writing. + * RESULT + * boolean - true if successful, false if not + ******/ +function safe_write_file($file, $content, $force_binary) { + $tmp_file = $file . "." . getmypid(); + $write_mode = $force_binary ? "wb" : "w"; + + $fd = fopen($tmp_file, $write_mode); + if (!$fd) { + // Unable to open temporary file for writing + return false; + } + if (!fwrite($fd, $content)) { + // Unable to write to temporary file + fclose($fd); + return false; + } + fclose($fd); + + if (!rename($tmp_file, $file)) { + // Unable to move temporary file to original + unlink($tmp_file); + return false; + } + return true; +} + +?>
\ No newline at end of file |