Skip to content

Commit

Permalink
Write configuration to temporary file first
Browse files Browse the repository at this point in the history
Currently when the runtime configuration is saved to file the true
configuration file is first truncated and then written to with each
available option.

If for any reason htop dies (e.g. program crash, or system shutdown)
while still performing the output the configuration file might end up
empty or corrupted.

Write to a temporary file and rename at the end on success.

As a side effect new configuration files are now created with a mode of
0600.
  • Loading branch information
cgzones authored and BenBE committed Nov 11, 2023
1 parent 69053ff commit 5e8fc97
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion Settings.c
Original file line number Diff line number Diff line change
Expand Up @@ -603,11 +603,16 @@ static void writeMeterModes(const Settings* this, FILE* fd, char separator, unsi
int Settings_write(const Settings* this, bool onCrash) {
FILE* fd;
char separator;
char *tmpFilename = NULL;
if (onCrash) {
fd = stderr;
separator = ';';
} else {
fd = fopen(this->filename, "w");
xAsprintf(&tmpFilename, "%s.tmp.XXXXXX", this->filename);
int fdtmp = mkstemp(tmpFilename);
if (fdtmp == -1)
return -errno;
fd = fdopen(fdtmp, "w");
if (fd == NULL)
return -errno;
separator = '\n';
Expand Down Expand Up @@ -719,6 +724,11 @@ int Settings_write(const Settings* this, bool onCrash) {
if (fclose(fd) != 0)
r = r ? r : -errno;

if (r == 0)
r = (rename(tmpFilename, this->filename) == -1) ? -errno : 0;

free(tmpFilename);

return r;
}

Expand Down

0 comments on commit 5e8fc97

Please sign in to comment.