xref: /linux/tools/testing/selftests/bpf/sysctl_helpers.c (revision eb0d6d97c27c29cd7392c8fd74f46edf7dff7ec2)
1*969fb456SEduard Zingerman // SPDX-License-Identifier: GPL-2.0
2*969fb456SEduard Zingerman #include <stdio.h>
3*969fb456SEduard Zingerman #include <errno.h>
4*969fb456SEduard Zingerman #include <string.h>
5*969fb456SEduard Zingerman 
6*969fb456SEduard Zingerman #include "sysctl_helpers.h"
7*969fb456SEduard Zingerman #include "test_progs.h"
8*969fb456SEduard Zingerman 
9*969fb456SEduard Zingerman int sysctl_set(const char *sysctl_path, char *old_val, const char *new_val)
10*969fb456SEduard Zingerman {
11*969fb456SEduard Zingerman 	int ret = 0;
12*969fb456SEduard Zingerman 	FILE *fp;
13*969fb456SEduard Zingerman 
14*969fb456SEduard Zingerman 	fp = fopen(sysctl_path, "r+");
15*969fb456SEduard Zingerman 	if (!fp)
16*969fb456SEduard Zingerman 		return -errno;
17*969fb456SEduard Zingerman 	if (old_val && fscanf(fp, "%s", old_val) <= 0) {
18*969fb456SEduard Zingerman 		ret = -ENOENT;
19*969fb456SEduard Zingerman 	} else if (!old_val || strcmp(old_val, new_val) != 0) {
20*969fb456SEduard Zingerman 		fseek(fp, 0, SEEK_SET);
21*969fb456SEduard Zingerman 		if (fprintf(fp, "%s", new_val) < 0)
22*969fb456SEduard Zingerman 			ret = -errno;
23*969fb456SEduard Zingerman 	}
24*969fb456SEduard Zingerman 	fclose(fp);
25*969fb456SEduard Zingerman 
26*969fb456SEduard Zingerman 	return ret;
27*969fb456SEduard Zingerman }
28*969fb456SEduard Zingerman 
29*969fb456SEduard Zingerman int sysctl_set_or_fail(const char *sysctl_path, char *old_val, const char *new_val)
30*969fb456SEduard Zingerman {
31*969fb456SEduard Zingerman 	int err;
32*969fb456SEduard Zingerman 
33*969fb456SEduard Zingerman 	err = sysctl_set(sysctl_path, old_val, new_val);
34*969fb456SEduard Zingerman 	if (err)
35*969fb456SEduard Zingerman 		PRINT_FAIL("failed to set %s to %s: %s\n", sysctl_path, new_val, strerror(-err));
36*969fb456SEduard Zingerman 	return err;
37*969fb456SEduard Zingerman }
38