1, in the terminal can be through the env, set command to view the current environment variables
2. The list of environment variables for the current process can be obtained by the third parameter in the main function.
int main (int argc, char *argv[], char *env[]);
Where argv and Env are an array of pointers, the last element of the array is null
3. Print the environment variables of the current process
int Main (int.Char char *env[]) { char **p = env; while (*p) {printf ("%s\n", *env); Env+ +; }}
4, getenv get the specified environment variable
char * GETENV ("Environment variable name")
int Main () { char * p = getenv ("PATH"); if(p) {printf ("%s", p); } Else{ return; }}
5. PUTENV Setting Environment variables
intMainintARGC,Char* * argv,Char**env) {printf ("%s\n", Getenv ("PATH")); Putenv ("Path=/home/hello"); printf ("%s\n", Getenv ("PATH"));}
Output Result:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/home/hello
6. SETENV Setting Environment variables
The first thing to note is that this function does not add or modify the environment variables of the shell process, or the environment variables set by the SETENV function are valid only in this process and in this execution. If the SETENV function is executed at one time when the program is run, the process terminates and runs the program again, the last setting is invalid, the last environment variable was not read.
SETENV ("Variable name", "New variable Value", "whether overriding")
intMainintARGC,Char* * argv,Char**env) {printf ("%s\n", Getenv ("PATH")); intres = setenv ("PATH","/home/hello",1); The third parameter, 1, represents an overrideif(res = =-1)return; printf ("%s\n", Getenv ("PATH"));}
Output Result:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/home/hello
If the third argument is 0, that is, the environment variable already exists, it does not change its value
Output Result:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
7. unsetenv Delete an environment variable
UNSETENV ("Environment variable name")
intMainintARGC,Char* * argv,Char**env) {printf ("%s\n", Getenv ("PATH")); Unsetenv ("PATH"); printf ("%s\n", Getenv ("PATH"));}
Output Result:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Path is deleted, so only one line is output
Functions related to environment variables in Linux