Linux 5 environment variables Programming

notes

Use the program to modify the current environment variables

Environment variables, parameters name for the environment variable name
char * getenv (const char * name )

Increase or set the system environment variable
putenv ()

Set the environment variable
int setenv (const char * name, const char * value, int overwrite); overwrite decide whether to overwrite the existing value * /

Revocation of the environment variable
unsetenv (const char * name)

example

makefile:

APP_NAME = environ
APP_OBJS = environ.o
CC = gcc
INC = ./
CFLAG += -g

.PHONY : all

all : $(APP_NAME)

$(APP_NAME) : $(APP_OBJS)
	$(CC) $(CFLAG) $(APP_OBJS) -o $(APP_NAME)
	
%.o : %.c
	$(CC) -c $(CFLAG) $^ -o $@

.PHONY : clean

clean :
	rm -f .o
	rm -f $(APP_NAME) $(APP_OBJS)

Source File:

/* environ.c */

#include <stdlib.h>
#include <stdio.h>

extern char ** environ;	/* 该变量保存系统变量的地址 */

int main()
{
	char **env = environ;
	
	while (*env)
	{
		printf("%s\n", *env);
		env++;
	}
	
	printf("\nPATH=%s\n", getenv("PATH"));	/* getenv获取某个环境变量的值 */
	
	putenv("ENVTEST=test_putenv");	/* putenv增加或改变环境变量的值 */
	printf("\nENVTEST=%s\n", getenv("ENVTEST"));
	
	/* int setenv(const char *name, const char *value, int overwrite); overwrite决定是否覆盖已经存在的值 */
	setenv("ENVTEST", "test_setenv", 1);
	printf("\nENVTEST=%s\n", getenv("ENVTEST"));
	
	unsetenv("ENVTEST");
	printf("\nENVTEST=%s\n", getenv("ENVTEST"));
	
	exit(0);
}

Guess you like

Origin blog.csdn.net/zzj244392657/article/details/92557485