setenv/unsetenv fix

Mark D. Anderson mda at discerning.com
Sat Dec 25 00:57:45 CET 2004


I got the latest release, couldn't compile on solaris due to reliance
on the bsd-ish setenv/unsetenv thing, and then saw on CVS
this is addressed by simply commenting out that functionality.

Seems like better would be to use the more portable getenv/putenv,
or to actually implement setenv/unsetenv when not available.

Below are bsd-licensed or public domain implementations of both,
that i put into my base/utils.c

-mda

/* top of file */
int setenv(const char *name, const char *value, int overwrite);
void unsetenv(const char *name);

/* anywhere */
/* see for example setenv.c in INN.
  http://www.mibsoftware.com/userkt/inn/dev/inn2.0-beta/inn/lib/setenv.c
*/
int setenv(const char *name, const char *value, int overwrite) {
  if (!overwrite && getenv(name) != NULL)
    return 0;
  char* e = malloc(strlen(name) + strlen(value) + 3);
  if (e == NULL) return -1;
  *e = 0;
  strcat(e, name);
  strcat(e, "=");
  strcat(e, value);
  return putenv(e);
  // should not free e, and we can't safely free any former value.
}

/* see
http://viewcvs.globus.org/viewcvs.cgi/gatekeeper/source/unsetenv.c?rev=HEAD&content-type=text/vnd.viewcvs-markup
 */
static char *
__findenv(name, offset)
     register const char *name;
     long *offset;
{
  extern char **environ;
  register int len;
  register const char *np;
  register char **p, *c;

  if (name == NULL || environ == NULL)
    return (NULL);
  for (np = name; *np && *np != '='; ++np)
    continue;
  len = np - name;
  for (p = environ; (c = *p) != NULL; ++p)
    if (strncmp(c, name, len) == 0 && c[len] == '=') {
      *offset = (long)(p - environ);
      return (c + len + 1);
    }
  return (NULL);
}
void
unsetenv(name)
     const char *name;
{
  extern char **environ;
  register char **p;
  long offset;

  while (__findenv(name, &offset))        /* if set multiple times */
    for (p = &environ[offset];; ++p)
      if (!(*p = *(p + 1)))
        break;
}


-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now. 
http://productguide.itmanagersjournal.com/




More information about the Developers mailing list