Setenv, unsetenv, putenv

I am working on a custom shell for a system programming class. We were instructed to implement built-in commands setenv()and unsetenv()with a hint about checking man pages for putenv().

My problem is that setenv(char*, char*, int)and putenv(char*)does not seem to work at all. My code to execute the entered command is as follows:

//... skipping past stuff for IO redirection
pid = fork();
if(pid == 0){
    //child
    if(!strcmp(_simpleCommands[0]->_arguments[0],"printenv")){
        //check if command is "printenv"
        extern char **environ;
        int i;
        for(i = 0; environ[i] != NULL; i++){
            printf("%s\n",environ[i]);
        }
        exit(0);
    }
    if(!strcmp(_simpleCommands[0]->_arguments[0],"setenv")){
        //if command is "setenv" get parameters char* A, char* B
        char * p = _simpleCommands[0]->_arguments[1];
        char * s = _simpleCommands[0]->_arguments[2];

        //putenv(char* s) needs to be formatted A=B; A is variable B is value
        char param[strlen(p) + strlen(s) + 1];
        strcat(param,p);
        strcat(param,"=");
        strcat(param,s);
        putenv(param);
        //setenv(p,s,1);
        exit(0);
    }
    if(!strcmp(_simpleCommands[0]->_arguments[0],"unsetenv")){
        //remove environment variable
        unsetenv(_simpleCommands[0]->_arguments[0]);
        exit(0);
    }
    //execute command
    execvp(_simpleCommands[0]->_arguments[0],_simpleCommands->_arguments);
    perror("-myshell");
    _exit(1);
}

//omitting restore IO defaults...

If I run printenvit works correctly, but if I try to set a new variable with putenv()or setenv()my command printenv()returns exactly the same thing, so it does not work.

, , , , (* ?), , , .

+5
2

, fork , . , . , , .

, C, . main, copy envp , execve. , - , , - setenv / putenv . . SO .

+5

, ? ... , .

, setevn prientevn .

#include <stdlib.h>
#include <assert.h>
int main()
{


 char * s= "stack=overflow";

 int ret =  putenv(s);

 assert(ret == 0);

 //printout all the env
 extern char **environ;
        int i;
        for(i = 0; environ[i] != NULL; i++){
            printf("%s\n",environ[i]);
        }


 return 0; 

}
pierr@ubuntu:~/workspace/so/c/env$ ./test | grep stack
stack=overflow
0

All Articles