- 论坛徽章:
- 0
|
自己实现env的功能,编译之后生成可执行文件foo,可是执行下面这行命令后,还是有输出:
ha@dell:~$ ./foo -i env
PWD=/home/ha
ha@dell:~$ |
为什么还有PWD这个环境变量呢?
附上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern char ** environ;
int showenv(char **env)
{
int i;
for (i = 0; NULL != env[i]; i++)
fprintf(stderr, "%s\n", env[i]);
return 0;
}
int main(int argc, char *argv[])
{
int off, env_count, leng, i;
char **new_env;
char *cmd = NULL;
if (1 == argc) {
showenv(environ);
return 0;
}
/* deal new environments */
env_count = 0;
off = 1;
if (!strcmp(argv[1], "-i"))
off = 2;
for (i = off; i < argc; i++)
if (NULL == strchr(argv[i], '='))
break;
env_count = i - off;
new_env = (char **)malloc((env_count + 1) * sizeof(char *));
if (NULL == new_env)
return -1;
new_env[env_count] = NULL;
for (i = 0; i < env_count; i++)
new_env[i] = argv[i + off];
/* deal commands */
i = off + env_count;
leng = 0;
if (i < argc) {
leng = strlen(argv[i]) + 1;
if (NULL == (cmd = (char *)malloc(leng))) {
free(new_env);
return -1;
}
strcpy(cmd, argv[i]);
}
for (i = i + 1; i < argc; i++) {
leng = leng + strlen(argv[i]) + 1;
if (NULL == (cmd = (char *)realloc(cmd, leng))) {
free(new_env);
return -1;
}
strcat(cmd, " ");
strcat(cmd, argv[i]);
}
if (NULL == cmd)
showenv(new_env);
else {
if (2 == off)
environ = new_env;
else {
for (i = 0; NULL != new_env[i]; i++) {
char *p = new_env[i];
while('=' != *p)
p++;
*p = '\0';
p++;
setenv(new_env[i], p, 1);
}
}
system(cmd);
free(cmd);
}
free(new_env);
return 0;
}
|
|
|