Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 1 | #include <stdlib.h> |
| 2 | #include <string.h> |
| 3 | #include <errno.h> |
| 4 | |
| 5 | int __putenv(char *s, int a); |
| 6 | |
| 7 | int setenv(const char *var, const char *value, int overwrite) |
| 8 | { |
| 9 | char *s; |
| 10 | int l1, l2; |
| 11 | |
Rich Felker | 649af9f | 2011-07-28 20:43:40 -0400 | [diff] [blame] | 12 | if (!var || !*var || strchr(var, '=')) { |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 13 | errno = EINVAL; |
| 14 | return -1; |
| 15 | } |
| 16 | if (!overwrite && getenv(var)) return 0; |
| 17 | |
| 18 | l1 = strlen(var); |
| 19 | l2 = strlen(value); |
| 20 | s = malloc(l1+l2+2); |
Rich Felker | 5437870 | 2013-10-04 15:49:55 -0400 | [diff] [blame^] | 21 | if (s) { |
| 22 | memcpy(s, var, l1); |
| 23 | s[l1] = '='; |
| 24 | memcpy(s+l1+1, value, l2); |
| 25 | s[l1+l2+1] = 0; |
| 26 | if (!__putenv(s, 1)) return 0; |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 27 | } |
Rich Felker | 5437870 | 2013-10-04 15:49:55 -0400 | [diff] [blame^] | 28 | free(s); |
| 29 | errno = ENOMEM; |
| 30 | return -1; |
Rich Felker | 0b44a03 | 2011-02-12 00:22:29 -0500 | [diff] [blame] | 31 | } |