Reputation: 1
I am trying to figure out how to export this environmental variables from my minishell to bash. Nothing happens when I use this code to export. Am I doing something wrong
if(strcmp(istring, "myexport") ==0) //This command shows parent enviornment
{
char * const *junk;
execve("/bin/bash" , junk , myexp);
return(1);
}
Upvotes: 0
Views: 5137
Reputation: 753695
If the intention is to run bash
in order to set the environment in your shell, you are misunderstanding how the environment is set.
There are the coding problems identified in the other answers:
junk
.myexp
.Assuming you get past those issues, though, the deeper one is that the child process cannot affect the environment of the parent process. When a shell exports an environment variable, it does so by adjusting a list that is supplied to each command it executes, but it is handled inside the shell, not by executing any external command.
Also, if the fragment shown is not run in a child process (after a fork()
), then you have another problem; execve()
does not return when the command executes successfully.
So, to export an environment variable, the change is made in the main shell, not in a sub-process.
Upvotes: 1
Reputation: 59997
Try
char *const argv = { "-c", "env", 0 };
char *const env = { "PATH=/bin", "USER=wibble", 0 };
execve("/bin/bash", argv, env);
And of course you can fetch things our of the existing environment by using extern char **environ;
or getenv
to construct the environment for the new binary/script.
Upvotes: 2
Reputation: 400254
You're passing an uninitialized pointer as the second argument to execve
—most likely, that will fail with EFAULT
, but if it does somehow magically succeed, bash
is going to see garbage in its argv
array of arguments and do something strange (most likely complain that some junk file doesn't exist).
If you don't want to pass any arguments, pass in a pointer to NULL
, but it's good practice to at least pass in the name of the program being executed as argv[0]
:
char *const argv[] = {"bash", NULL};
execve("/bin/bash", argv, myexp);
Also, what is myexp
? Is it a pointer to a NULL
-terminated array of pointers to strings of the form FOO=BAR
?
Upvotes: 0