[PATCH v2 2/3] env: let setenv() take printf arguments

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



It's a common pattern to (ba)sprintf to a string and then call setenv()
with this string. Introduce pr_setenv() as a shortcut to simplify this
pattern.

Signed-off-by: Sascha Hauer <s.hauer@xxxxxxxxxxxxxx>
---
 common/env.c          | 32 ++++++++++++++++++++++++++++++--
 include/environment.h |  7 +++++++
 2 files changed, 37 insertions(+), 2 deletions(-)

diff --git a/common/env.c b/common/env.c
index 05add63f62..141cd66046 100644
--- a/common/env.c
+++ b/common/env.c
@@ -244,13 +244,12 @@ static int dev_setenv(const char *name, const char *val)
 
 /**
  * setenv - set environment variables
- * @_name - Variable name
+ * @name - Variable name
  * @value - the value to set, empty string not handled specially
  *
  * Returns 0 for success and a negative error code otherwise
  * Use unsetenv() to unset.
  */
-
 int setenv(const char *_name, const char *value)
 {
 	char *name = strdup(_name);
@@ -277,6 +276,35 @@ out:
 }
 EXPORT_SYMBOL(setenv);
 
+/**
+ * pr_setenv - set environment variables
+ * @name - Variable name
+ * @fmt - the format string to use
+ *
+ * Returns 0 for success and a negative error code otherwise
+ * Use unsetenv() to unset.
+ */
+int pr_setenv(const char *name, const char *fmt, ...)
+{
+	va_list ap;
+	int ret = 0;
+	char *value;
+	int len;
+
+	va_start(ap, fmt);
+	len = vasprintf(&value, fmt, ap);
+	va_end(ap);
+
+	if (len < 0)
+		return -ENOMEM;
+
+	ret = setenv(name, value);
+	free(value);
+
+	return ret;
+}
+EXPORT_SYMBOL(setenv);
+
 int export(const char *varname)
 {
 	const char *val = getenv_raw(&context->local, varname);
diff --git a/include/environment.h b/include/environment.h
index 19e522cfb6..1557c3a1d7 100644
--- a/include/environment.h
+++ b/include/environment.h
@@ -32,6 +32,7 @@ char *var_name(struct variable_d *);
 #ifdef CONFIG_ENVIRONMENT_VARIABLES
 const char *getenv(const char *);
 int setenv(const char *, const char *);
+int pr_setenv(const char *, const char *fmt, ...)  __attribute__ ((format(__printf__, 2, 3)));
 void export_env_ull(const char *name, unsigned long long val);
 int getenv_ull(const char *name, unsigned long long *val);
 int getenv_ul(const char *name, unsigned long *val);
@@ -49,6 +50,12 @@ static inline int setenv(const char *var, const char *val)
 	return 0;
 }
 
+static inline __attribute__ ((format(__printf__, 2, 3))) int pr_setenv(
+	const char *var, const char *fmt, ...)
+{
+	return 0;
+}
+
 static inline void export_env_ull(const char *name, unsigned long long val) {}
 
 static inline int getenv_ull(const char *name, unsigned long long *val)
-- 
2.30.2





[Index of Archives]     [Linux Embedded]     [Linux USB Devel]     [Linux Audio Users]     [Yosemite News]     [Linux Kernel]     [Linux SCSI]     [XFree86]

  Powered by Linux