atomic file saves

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • CptDondo

    atomic file saves

    I have an embedded system that will save configuration files based on
    user input. This device will be used in areas that have uncertain
    power, and a battery backup is not a realistic option.

    It is not critical that the user's latest changes be saved, but it is
    critical that the system have a valid configuration file, so I want to
    minimize the chances of having a corrupt config file.

    I've come up with this:

    $oldConfFile = $confFile . ".bak";
    $newConfFile = $confFile . ".new";
    $fp = fopen($newConfF ile, "w");
    // FIXME error message here
    if ($fp == false ) return array();
    fputs($fp, $newConfig);
    fclose($fp);
    rename($confFil e,$oldConfFile) ;
    rename($newConf File,$confFile) ;

    which is about as atomic as I can think of.... And I can do some
    checking on boot and (possibly) copy either the .bak or the .new file
    over to the config file if it is valid and the main config file is not.

    Can anyone offer any comments or suggestions for making this more robust?
  • .:[ ikciu ]:.

    #2
    Re: atomic file saves

    Zebrawszy mysli CptDondo <yan@NsOeSiPnAe Mr.comwyklepal:
    $oldConfFile = $confFile . ".bak";
    $newConfFile = $confFile . ".new";
    $fp = fopen($newConfF ile, "w");
    // FIXME error message here
    if ($fp == false ) return array();
    fputs($fp, $newConfig);
    fclose($fp);
    rename($confFil e,$oldConfFile) ;
    rename($newConf File,$confFile) ;


    if (!$fp = fopen($newConfF ile, 'w')) {
    return array();
    }
    if (fwrite($fp, $newConfig) === FALSE) {
    return array();
    }
    fclose($fp);
    //ofc if you have rights to rename files
    rename($confFil e,$oldConfFile) ;
    rename($newConf File,$confFile) ;

    or / and you can use try{
    ... your code...
    }catch(Exceptio n e){
    return array();
    }


    --
    ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~
    Ikciu | gg: 718845 | www: www.e-irsa.pl

    2be || !2be $this =mysql_query();


    Comment

    Working...