Linux environment programming-environment variables & print environment variables

In the topic of shell programming, we have roughly introduced environment variables and local variables.

Let’s give a specific introduction today. What exactly are environment variables?

Let's have a video to understand who it is

it's me

 

1. The meaning & characteristics of environment variables

Environment variables refer to the following parameters used in the operating system to specify the operating environment of the operating system

1) Features:

  1. String
  2. There is a unified format: name=value[:value]
  3. Value used to describe the environmental information of the process

2) Usage form: similar to command line parameters

3) Storage format: similar to command line parameters, char* [] array, array name environ, internal storage string, NULL as sentinel

4) Load position: similar to command line parameters, located in the user area, higher than the starting position of the stack area

5) Introduce the environment variable table: the environment variable must be declared extern char** environ;

 

Code Demo

#include <iostream>

extern char **environ;

int
main(int argc, char *argv[])
{
	int i;
	for(i=0; environ[i]; i++){
		printf("%s\n", environ[i]);
	}
	return 0;
}

 ./echoPath The effect is as follows

 Below we are introducing two functions about environment variables

char *getenv(const char* name); Get the environment variable named name

int setenv(const char* name, const char* value, int overwrite);  // return 0(success), -1(err)

        overwrite 1: Overwrite the original environment variables

                          0: Do not overwrite, changing parameters is often used to set new environment variables

#include <iostream>
#include <stdlib.h>

using namespace std;

int
main(int argc, char* argv[])
{
	char *path_value = NULL;
	const char* path_name = "ABC";
	if(path_value = getenv(path_name)){
		printf("name: %s, value:%s \n", path_value, path_value);
	}else{
		printf("the %s path is not exist \n", path_name);
	}
	int   ret = setenv(path_name, "yyyy-mm-dd", 1);
	if(ret == 0){
		printf("set environment success \n");
	}else{
		cerr << "setenv error" << endl;
	}

	if(path_value = getenv(path_name)){
		printf("name: %s, value:%s \n", path_value, path_value);
	}else{
		printf("the %s path is not exist \n", path_name);
	}

	#if 1
		ret = unsetenv(path_name);
		if(ret == 0){
			cout << " unsetenv success" << endl;
			if(path_value = getenv(path_name)){
				printf("name: %s, value:%s \n", path_value, path_value);
			}
		}else{
			cerr << "unsetenv error" << endl;
		}
		
	#endif 

	return 0;
}

running result:

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_44065088/article/details/108529902