View methods to control environment variables under Linux
- 2020-06-07 05:54:36
- OfStack
View environment variables
View an environment variable: For example, we need to view the environment variable HOME, we can directly enter echo $HOME under shell, we can print out all the environment variables and the value of the environment variable
Print environment variable
The global variable environ defined in libc refers to the environment variable scale. environ is not included in any header file and is declared in extern when used.
A program print environment variable is provided below
#include<stdio.h>
int main()
{
//libc Global variables defined in environ Directional environmental variability scale ,environ Not included in any header ⽂ In the file , so
// In making ⽤ when to ⽤ with extern The statement.
extern char** environ;
// while(environ)
// {
// printf("%s\n",*environ++);
// }
// printf("hah");
int i = 0;
for(i = 0;environ[i]!=NULL;i++)
{
printf("%s\n",environ[i]);
}
return 0;
}
Controls the environment variable interface
getenv
.
setenv
.
unsetenv
getenv () function
#include <stdlib.h>
char *getenv(const char *name);
The getenv() function's search environment list finds the environment variable name and returns a pointer to the corresponding value string. If not, return NULL
The setenv() function and unsetenv
#include <stdlib.h>
int setenv(const char *name, const char *value, int overwrite);
int unsetenv(const char *name);
setenv() sets the environment variable to return 0 on success or non-0 on failure
unsetenv() removes 1 environment variable
The following provides a section of procedures you can test 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char* val;
const char* name ="ABC";
// To obtain ABC The value of an environment variable
val = getenv(name);
printf("No.1 %s=%s\n", name, val);
// Override the write environment variable
setenv(name, "I amsure of that I will get it", 1);
printf("No.2%s=%s\n", name, val);
val = getenv(name);
printf("No.3%s=%s\n", name, val);
// delete 1 Environment variables
int ret =unsetenv("ABC");
printf("ret =%d\n",ret);
val = getenv(name);
printf("No.3 %s=%s\n",name, val);
return 0;
}