diff options
author | Tom Lane <tgl@sss.pgh.pa.us> | 2004-05-05 21:18:29 +0000 |
---|---|---|
committer | Tom Lane <tgl@sss.pgh.pa.us> | 2004-05-05 21:18:29 +0000 |
commit | 9e16195f3f7f3cf7815200869be936bfcecfa333 (patch) | |
tree | 01ca518fde7c26405307abac5926ec0e1e9013a0 /src/port/unsetenv.c | |
parent | dadce6509a17d510c62414e033e2491ed50a9fcb (diff) |
Second try at a portable unsetenv().
Diffstat (limited to 'src/port/unsetenv.c')
-rw-r--r-- | src/port/unsetenv.c | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/src/port/unsetenv.c b/src/port/unsetenv.c new file mode 100644 index 00000000000..122fb3f9ea2 --- /dev/null +++ b/src/port/unsetenv.c @@ -0,0 +1,56 @@ +/*------------------------------------------------------------------------- + * + * unsetenv.c + * unsetenv() emulation for machines without it + * + * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * $PostgreSQL: pgsql/src/port/unsetenv.c,v 1.1 2004/05/05 21:18:29 tgl Exp $ + * + *------------------------------------------------------------------------- + */ + +#include "c.h" + + +void +unsetenv(const char *name) +{ + char *envstr; + + if (getenv(name) == NULL) + return; /* no work */ + + /* + * The technique embodied here works if libc follows the Single Unix Spec + * and actually uses the storage passed to putenv() to hold the environ + * entry. When we clobber the entry in the second step we are ensuring + * that we zap the actual environ member. However, there are some libc + * implementations (notably recent BSDs) that do not obey SUS but copy + * the presented string. This method fails on such platforms. Hopefully + * all such platforms have unsetenv() and thus won't be using this hack. + * + * Note that repeatedly setting and unsetting a var using this code + * will leak memory. + */ + + envstr = (char *) malloc(strlen(name) + 2); + if (!envstr) /* not much we can do if no memory */ + return; + + /* Override the existing setting by forcibly defining the var */ + sprintf(envstr, "%s=", name); + putenv(envstr); + + /* Now we can clobber the variable definition this way: */ + strcpy(envstr, "="); + + /* + * This last putenv cleans up if we have multiple zero-length names + * as a result of unsetting multiple things. + */ + putenv(envstr); +} |