putenv.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright (C) 1995,1996 Robert de Bath <rdebath@cix.compulink.co.uk>
  2. * This file is part of the Linux-8086 C library and is distributed
  3. * under the GNU Library General Public License.
  4. */
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <malloc.h>
  8. extern char **environ;
  9. #define ADD_NUM 4
  10. int putenv(var)
  11. const char *var;
  12. {
  13. static char **mall_env = 0;
  14. static int extras = 0;
  15. char **p, **d;
  16. char *r;
  17. int len;
  18. r = strchr(var, '=');
  19. if (r == 0)
  20. len = strlen(var);
  21. else
  22. len = r - var;
  23. if (!environ) {
  24. environ = (char **) malloc(ADD_NUM * sizeof(char *));
  25. memset(environ, 0, sizeof(char *) * ADD_NUM);
  26. extras = ADD_NUM;
  27. }
  28. for (p = environ; *p; p++) {
  29. if (memcmp(var, *p, len) == 0 && (*p)[len] == '=') {
  30. while ((p[0] = p[1]))
  31. p++;
  32. extras++;
  33. break;
  34. }
  35. }
  36. if (r == 0)
  37. return 0;
  38. if (extras <= 0) { /* Need more space */
  39. d = malloc((p - environ + 1 + ADD_NUM) * sizeof(char *));
  40. if (d == 0)
  41. return -1;
  42. memcpy((void *) d, (void *) environ,
  43. (p - environ + 1) * sizeof(char *));
  44. p = d + (p - environ);
  45. extras = ADD_NUM;
  46. if (mall_env)
  47. free(mall_env);
  48. environ = d;
  49. mall_env = d;
  50. }
  51. *p++ = strdup((char *) var);
  52. *p = '\0';
  53. extras--;
  54. return 0;
  55. }