util-lib: optionally, when writing a string to a file, verify string on failure
With this change, the idiom:
r = write_string_file(p, buf, 0);
if (r < 0) {
if (verify_one_line_file(p, buf) > 0)
r = 0;
}
gets reduced to:
r = write_string_file(p, buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE);
i.e. when writing the string fails and the new flag
WRITE_STRING_FILE_VERIFY_ON_FAILURE is specified we'll not return a
failure immediately, but check the contents of the file. If it matches
what we wanted to write we suppress the error and exit cleanly.
This commit is contained in:
@@ -363,6 +363,26 @@ static void test_write_string_file_no_create(void) {
|
||||
unlink(fn);
|
||||
}
|
||||
|
||||
static void test_write_string_file_verify(void) {
|
||||
_cleanup_free_ char *buf = NULL, *buf2 = NULL;
|
||||
int r;
|
||||
|
||||
assert_se(read_one_line_file("/proc/cmdline", &buf) >= 0);
|
||||
assert_se((buf2 = strjoin(buf, "\n", NULL)));
|
||||
|
||||
r = write_string_file("/proc/cmdline", buf, 0);
|
||||
assert_se(r == -EACCES || r == -EIO);
|
||||
r = write_string_file("/proc/cmdline", buf2, 0);
|
||||
assert_se(r == -EACCES || r == -EIO);
|
||||
|
||||
assert_se(write_string_file("/proc/cmdline", buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE) == 0);
|
||||
assert_se(write_string_file("/proc/cmdline", buf2, WRITE_STRING_FILE_VERIFY_ON_FAILURE) == 0);
|
||||
|
||||
r = write_string_file("/proc/cmdline", buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_AVOID_NEWLINE);
|
||||
assert_se(r == -EACCES || r == -EIO);
|
||||
assert_se(write_string_file("/proc/cmdline", buf2, WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
|
||||
}
|
||||
|
||||
static void test_load_env_file_pairs(void) {
|
||||
char fn[] = "/tmp/test-load_env_file_pairs-XXXXXX";
|
||||
int fd;
|
||||
@@ -419,6 +439,7 @@ int main(int argc, char *argv[]) {
|
||||
test_write_string_stream();
|
||||
test_write_string_file();
|
||||
test_write_string_file_no_create();
|
||||
test_write_string_file_verify();
|
||||
test_load_env_file_pairs();
|
||||
|
||||
return 0;
|
||||
|
||||
Reference in New Issue
Block a user