Implement streplace()

Restore variable as early as possible and in error conditions
This commit is contained in:
sin 2014-04-17 16:38:31 +01:00
parent 6ba9fe35f1
commit 0897d999e6
1 changed files with 16 additions and 8 deletions

View File

@ -7,6 +7,16 @@
#include <unistd.h> #include <unistd.h>
#include "util.h" #include "util.h"
static void
streplace(char *s, int a, int b)
{
char *p;
for (p = s; *p; p++)
if (*p == a)
*p = b;
}
static int static int
getsysctl(char *variable, char **value) getsysctl(char *variable, char **value)
{ {
@ -17,13 +27,15 @@ getsysctl(char *variable, char **value)
ssize_t n; ssize_t n;
size_t sz, i; size_t sz, i;
for (p = variable; *p; p++) streplace(variable, '.', '/');
if (*p == '.')
*p = '/';
strlcpy(path, "/proc/sys/", sizeof(path)); strlcpy(path, "/proc/sys/", sizeof(path));
if (strlcat(path, variable, sizeof(path)) >= sizeof(path)) if (strlcat(path, variable, sizeof(path)) >= sizeof(path)) {
streplace(variable, '/', '.');
return -1; return -1;
}
streplace(variable, '/', '.');
fd = open(path, O_RDONLY); fd = open(path, O_RDONLY);
if (fd < 0) if (fd < 0)
@ -59,10 +71,6 @@ getsysctl(char *variable, char **value)
if (p) if (p)
*p = '\0'; *p = '\0';
for (p = variable; *p; p++)
if (*p == '/')
*p = '.';
*value = buf; *value = buf;
close(fd); close(fd);