1 /* 2 * Copyright (c) 1987 Regents of the University of California. 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms are permitted 6 * provided that this notice is preserved and that due credit is given 7 * to the University of California at Berkeley. The name of the University 8 * may not be used to endorse or promote products derived from this 9 * software without specific prior written permission. This software 10 * is provided ``as is'' without express or implied warranty. 11 */ 12 13 #if defined(LIBC_SCCS) && !defined(lint) 14 static char sccsid[] = "@(#)setenv.c 5.1 (Berkeley) 12/24/87"; 15 #endif /* LIBC_SCCS and not lint */ 16 17 #include <sys/types.h> 18 #include <stdio.h> 19 20 /* 21 * setenv -- 22 * Set the value of the environmental variable "name" to be 23 * "value". If rewrite is set, replace any current value. 24 */ 25 setenv(name, value, rewrite) 26 register char *name, *value; 27 int rewrite; 28 { 29 extern char **environ; 30 static int alloced; /* if allocated space before */ 31 register char *C; 32 int l_value, offset; 33 char *malloc(), *realloc(), *_findenv(); 34 35 if (*value == '=') /* no `=' in value */ 36 ++value; 37 l_value = strlen(value); 38 if ((C = _findenv(name, &offset))) { /* find if already exists */ 39 if (!rewrite) 40 return(0); 41 if (strlen(C) >= l_value) { /* old larger; copy over */ 42 while (*C++ = *value++); 43 return(0); 44 } 45 } 46 else { /* create new slot */ 47 register int cnt; 48 register char **P; 49 50 for (P = environ, cnt = 0; *P; ++P, ++cnt); 51 if (alloced) { /* just increase size */ 52 environ = (char **)realloc((char *)environ, 53 (u_int)(sizeof(char *) * (cnt + 2))); 54 if (!environ) 55 return(-1); 56 } 57 else { /* get new space */ 58 alloced = 1; /* copy old entries into it */ 59 P = (char **)malloc((u_int)(sizeof(char *) * 60 (cnt + 2))); 61 if (!P) 62 return(-1); 63 bcopy(environ, P, cnt * sizeof(char *)); 64 environ = P; 65 } 66 environ[cnt + 1] = NULL; 67 offset = cnt; 68 } 69 for (C = name; *C && *C != '='; ++C); /* no `=' in name */ 70 if (!(environ[offset] = /* name + `=' + value */ 71 malloc((u_int)((int)(C - name) + l_value + 2)))) 72 return(-1); 73 for (C = environ[offset]; (*C = *name++) && *C != '='; ++C); 74 for (*C++ = '='; *C++ = *value++;); 75 return(0); 76 } 77 78 /* 79 * unsetenv(name) -- 80 * Delete environmental variable "name". 81 */ 82 void 83 unsetenv(name) 84 char *name; 85 { 86 extern char **environ; 87 register char **P; 88 int offset; 89 90 while (_findenv(name, &offset)) /* if set multiple times */ 91 for (P = &environ[offset];; ++P) 92 if (!(*P = *(P + 1))) 93 break; 94 } 95