diff options
author | Bill Marquette <billm@pfsense.org> | 2008-05-17 19:02:08 +0000 |
---|---|---|
committer | Bill Marquette <billm@pfsense.org> | 2008-05-17 19:02:08 +0000 |
commit | 90d32f5d62aea9f8964fa96be67828afc79b8cdb (patch) | |
tree | fb270d5bad9f56a33328758f3861f9d16c194693 /etc/inc/pfsense-utils.inc | |
parent | 7b6f313392f8ebea65803d66882287b031555425 (diff) | |
download | pfsense-90d32f5d62aea9f8964fa96be67828afc79b8cdb.zip pfsense-90d32f5d62aea9f8964fa96be67828afc79b8cdb.tar.gz |
MFC of changeset [22584]
Atomic file writing
Patch-by: David Rees
Diffstat (limited to 'etc/inc/pfsense-utils.inc')
-rw-r--r-- | etc/inc/pfsense-utils.inc | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/etc/inc/pfsense-utils.inc b/etc/inc/pfsense-utils.inc index 7c92560..47854d5 100644 --- a/etc/inc/pfsense-utils.inc +++ b/etc/inc/pfsense-utils.inc @@ -3621,4 +3621,44 @@ function is_wan_interface_up($interface) { return false; } +/****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; +} + + ?> |