/* * unsetenv(name) -- * Delete environmental variable "name". */ int unsetenv(const char *name) { size_t l_name; ssize_t r_offset, w_offset; _DIAGASSERT(name != NULL); l_name = __envvarnamelen(name, false); if (l_name == 0) { errno = EINVAL; return -1; } if (!__writelockenv()) return -1; /* Search for the given name in the environment. */ r_offset = __getenvslot(name, l_name, false); if (r_offset == -1) { /* Not found. */ (void)__unlockenv(); return 0; } __freeenvvar(environ[r_offset]); /* * Remove all matches from the environment and free the associated * memory if possible. */ w_offset = r_offset; while (environ[++r_offset] != NULL) { if (strncmp(environ[r_offset], name, l_name) != 0 || environ[r_offset][l_name] != '=') { /* Not a match, keep this entry. */ environ[w_offset++] = environ[r_offset]; } else { /* We found another match. */ __freeenvvar(environ[r_offset]); } } /* Clear out remaining stale entries in the environment vector. */ do { environ[w_offset++] = NULL; } while (w_offset < r_offset); (void)__unlockenv(); return 0; }
int putenv(char *str) { size_t l_name; int rv; _DIAGASSERT(str != NULL); l_name = __envvarnamelen(str, true); if (l_name == 0) { errno = EINVAL; return -1; } rv = -1; if (__writelockenv()) { ssize_t offset; offset = __getenvslot(str, l_name, true); if (offset != -1) { if (environ[offset] != NULL) __freeenvvar(environ[offset]); environ[offset] = str; rv = 0; } (void)__unlockenv(); } return rv; }