implement platform abstraction of unsetenv()

This commit is contained in:
Axel Kohlmeyer
2021-10-22 11:05:32 -04:00
parent 69f5e1feac
commit 5c9a4f4be0
5 changed files with 41 additions and 6 deletions

View File

@ -115,6 +115,9 @@ Environment variable functions
.. doxygenfunction:: putenv
:project: progguide
.. doxygenfunction:: unsetenv
:project: progguide
.. doxygenfunction:: list_pathenv
:project: progguide

View File

@ -442,6 +442,27 @@ int platform::putenv(const std::string &vardef)
return -1;
}
/* ----------------------------------------------------------------------
unset environment variable
------------------------------------------------------------------------- */
int platform::unsetenv(const std::string &variable)
{
if (variable.size() == 0) return -1;
#ifdef _WIN32
// empty _putenv() definition deletes variable on Windows
// must not have an equal sign as that will result in creating an environment variable
if (variable.find_first_of('=') != std::string::npos) return -1;
auto var = utils::strdup(variable);
int rv = _putenv(var);
delete[] var;
return rv;
#else
return ::unsetenv(variable.c_str());
#endif
}
/* ----------------------------------------------------------------------
split a "path" environment variable into a list
------------------------------------------------------------------------- */

View File

@ -116,6 +116,13 @@ namespace platform {
int putenv(const std::string &vardef);
/*! Delete variable from the environment
*
* \param variable variable name
* \return -1 if failure otherwise 0 */
int unsetenv(const std::string &variable);
/*! Get list of entries in a path environment variable
*
* This provides a list of strings of the entries in an environment

View File

@ -363,11 +363,7 @@ TEST(LAMMPS_init, NoOpenMP)
FILE *fp = fopen("in.lammps_class_noomp", "w");
fputs("\n", fp);
fclose(fp);
#if defined(__WIN32)
_putenv("OMP_NUM_THREADS");
#else
unsetenv("OMP_NUM_THREADS");
#endif
platform::unsetenv("OMP_NUM_THREADS");
const char *args[] = {"LAMMPS_init", "-in", "in.lammps_class_noomp", "-log", "none", "-nocite"};
char **argv = (char **)args;

View File

@ -37,7 +37,7 @@ TEST(Platform, clock)
ASSERT_GT(ct_used, 1e-4);
}
TEST(Platform, putenv)
TEST(Platform, putenv_unsetenv)
{
const char *var = getenv("UNITTEST_VAR1");
ASSERT_EQ(var, nullptr);
@ -65,6 +65,14 @@ TEST(Platform, putenv)
ASSERT_THAT(var, StrEq("one=two"));
ASSERT_EQ(platform::putenv(""), -1);
ASSERT_EQ(platform::unsetenv(""), -1);
ASSERT_EQ(platform::unsetenv("UNITTEST_VAR3=two"), -1);
var = getenv("UNITTEST_VAR1");
ASSERT_NE(var, nullptr);
ASSERT_EQ(platform::unsetenv("UNITTEST_VAR1"), 0);
var = getenv("UNITTEST_VAR1");
ASSERT_EQ(var, nullptr);
}
TEST(Platform, list_pathenv)