Plan 9 from Bell Labs’s /usr/web/sources/contrib/rsc/linuxemu/libc/linux/9/getenv.c

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


#include <u.h>
#include <libc.h>

extern char	**environ;

char *
getenv(char *name)
{
	char **p;
	int n;

	n = strlen(name);
	for(p = environ; *p != 0; p++) {
		if(strncmp(name, *p, n) == 0 && (*p)[n] == '=')
			return *p+n+1;
	}
	return 0;
}

static int	firstalloc = 1;
/*
 *	put a string of the form "name=val" into the environment
 */
int
putenv(char *name, char *val)
{
	char **p, *new;
	int n, l;

	new = malloc(strlen(name)+1+strlen(val)+1);
	if(new == 0)
		return -1;

	strcpy(new, name);
	strcat(new, "=");
	strcat(new, val);

	l = strlen(name);
	for(p = environ; *p; p++)
		if(strncmp(name, *p, l) == 0 && (*p)[l] == '=') {
			*p = new;
			return 0;
		}

	/* not currently in the environment */
	n = p-environ+2;
	if(!firstalloc) {
		p = realloc(environ, n*sizeof(char*));
		if(p == 0)
			return -1;
		environ = p;
	} else {
		firstalloc = 0;
		p = malloc(n*sizeof(char*));
		if(p == 0)
			return -1;
		memmove(p, environ, n*sizeof(char*));
		environ = p;
	}
	environ[n-2] = new;
	environ[n-1] = 0;
	return 0;
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.