Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the use of the third, environment variable argument to the C++ main()?

I have come to understand that char **envp is the third argument to main, and with the help of the code below, I was able to see what it actually contains.

int main(int argc, char *argv[], char *env[])
{
  int i;
  for (i=0 ; env[i] ; i++)
    std::cout << env[i] << std::endl;
  std::cout << std::endl;
}

My question is: why (in what situations) would programmers need to use this? I have found many explanations for what this argument does, but nothing that would tell me where this is typically used. Trying to understand what kind of real world situations this might be used in.

like image 897
aspen100 Avatar asked Oct 05 '13 14:10

aspen100


2 Answers

It is an array containing all the environmental variables. It can be used for example to get the user name or home directory of current logged in user. One situation is, for example, if I want to hold a configuration file in user's home directory and I need to get the PATH;

int main(int argc, char* argv[], char* env[]){

std::cout << env[11] << '\n';  //this prints home directory of current user(11th for me was the home directory)

return 0;
}

Equivalent of env is char* getenv (const char* name) function which is easier to use, for example:

 std::cout << getenv("USER");

prints user name of current user.

like image 188
khajvah Avatar answered Sep 21 '22 18:09

khajvah


The getenv() function allows you to find the value of a specific environment variable, but doesn't provide a mechanism to scan over the entire list of environment variables. The envp argument allows you to iterate over the entire list of environment variables, as your demonstration code shows which is simply not feasible using the getenv() interface.

On POSIX systems, there is a global variable, extern char **environ;, which also points to the environment. The functions putenv() (ancient, non-preferred because it presents memory management problems), setenv() and unsetenv() can also manipulate the environment variable list (as defined by environ). A program can directly modify environ or the values it points at, but that is not advisable.

If you are using fork() and the exec*() family of functions, unless you use execve() and specify the environment explicitly, the child process will receive the environment defined by environ.

No header declares environ — AFAIK, it is the only variable defined by POSIX without a header to declare it. The C standard recognizes the int main(int argc, char **argv, char **envp) signature for main() as a common extension to the standard, documented in Annex J.

like image 39
Jonathan Leffler Avatar answered Sep 21 '22 18:09

Jonathan Leffler