putenv.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <errno.h>
  4. #include <stdio.h>
  5. extern char **__environ;
  6. char **__env_map;
  7. int __putenv(char *s, int a)
  8. {
  9. int i=0, j=0;
  10. char *end = strchr(s, '=');
  11. size_t l = end-s+1;
  12. char **newenv = 0;
  13. char **newmap = 0;
  14. static char **oldenv;
  15. if (!end || l == 1) return -1;
  16. for (; __environ[i] && memcmp(s, __environ[i], l); i++);
  17. if (a) {
  18. if (!__env_map) {
  19. __env_map = calloc(2, sizeof(char *));
  20. if (__env_map) __env_map[0] = s;
  21. } else {
  22. for (; __env_map[j] && __env_map[j] != __environ[i]; j++);
  23. if (!__env_map[j]) {
  24. newmap = realloc(__env_map, sizeof(char *)*(j+2));
  25. if (newmap) {
  26. __env_map = newmap;
  27. __env_map[j] = s;
  28. __env_map[j+1] = NULL;
  29. }
  30. } else {
  31. free(__env_map[j]);
  32. }
  33. }
  34. }
  35. if (!__environ[i]) {
  36. newenv = malloc(sizeof(char *)*(i+2));
  37. if (!newenv) {
  38. if (a && __env_map) __env_map[j] = 0;
  39. return -1;
  40. }
  41. memcpy(newenv, __environ, sizeof(char *)*i);
  42. newenv[i] = s;
  43. newenv[i+1] = 0;
  44. __environ = newenv;
  45. free(oldenv);
  46. oldenv = __environ;
  47. }
  48. __environ[i] = s;
  49. return 0;
  50. }
  51. int putenv(char *s)
  52. {
  53. return __putenv(s, 0);
  54. }