#Linux中的GCC规划# Environment variables and non-local jumps

1 The origin of the environmental table

  1. First of all, we have learned from the previous article that the startup routine passes three things (argc, argv, envp) to the main function.
int main(int argc,char *argv[] ,char* envp[])h
argc 是 参数的个数。
argv是 参数表。
envp是环境表。

2 Format of the environment table

环境表:初始时,继承于父进程
extern char** environ;
其中包括有 :============
“HOME=/home/Kshine”
"PATH=/bin:/usr/bin"
"SHELL=/bin/bash"
"USER=Kshine"
"MAIL=/var/mail/kshine"
。。。。
。。。。
。。。。
。。。。
NULL
=====================

3 Get the test code of the environment table

  1. code show as below:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
extern char **environ;//导入该变量
int main(int argc,char* argv[]){
	int i=0;
	char* ptr = environ[i];//指向第一个环境变量等式
	while(ptr!=NULL){
		printf("%s\n",ptr)
	}
	return 0;
}

  1. operation result:
kshine@kshine-virtual-machine:~/桌面$ vi test_environ.c
kshine@kshine-virtual-machine:~/桌面$ gcc test_environ.c -o te -Wall
kshine@kshine-virtual-machine:~/桌面$ ./te
SSH_AGENT_PID=2215
GPG_AGENT_INFO=/tmp/keyring-8rYgpt/gpg:0:1
TERM=xterm
SHELL=/bin/bash
...
...(此处省略)
...
DISPLAY=:0.0
XDG_CURRENT_DESKTOP=Unity
GTK_IM_MODULE=ibus
LESSCLOSE=/usr/bin/lesspipe %s %s
COLORTERM=gnome-terminal
XAUTHORITY=/home/kshine/.Xauthority
OLDPWD=/home/kshine
_=./te

4 Environment variable operation function

  1. head File
#include <stdlib.h>
  1. Several related functions
(1)获取环境变量值
char *getenv(const char *name);

(2)放入“name = value”形式的字符串。(覆盖),成功返回0,失败返回-1
int putenv(char*str);

(3)设置具体的name的value。(rewrite决定是否覆盖),成功返回0,失败返回-1
int setenv(const char *name,const char * value,int rewrite);

(4)删除name的定义(无论是否存在),成功返回0,失败返回-1
int unsetenv(const char* name);

5 Non-local jump

In C program, to do exception handling, jump is needed.
We know that when doing a jump inside a function (partial jump), goto is used .
If you want to perform a non-local jump , you need to use the jump function longjmp .

  1. head File
#include <setjmp.h>
  1. related functions
(1) 设置非局部跳转的跳转点
int setjmp(jmp_buf env);

(2) 进行非局部跳转,val作为返回值
void longjmp(jmp_buf env,int val);
  1. Pay attention to the
    env parameter:
    (1) Special type jmp_buf.
    (2) When calling longjmp, store all the information used to restore the stack state.
    After longjmp non-local jump:
    (1) Global variables, static variables, and volatile variables cannot be restored to their original values.
    (2) Register variables can be restored to their original values.
    (3) The automatic variable (auto) may be restored to its original value after optimized compilation.

Guess you like

Origin blog.csdn.net/Kshine2017/article/details/103885567