linux环境变量、environ、getenv、setenv、unsetenv

linux环境变量

每个进程运行都有自己的环境变量。也可以认为,shell及其在该shell中运行的子进程共用的变量,称为环境变量。一个进程的变量有很多,分为该进程的自定义变量,及其环境变量。

shell获取环境变量

环境变量相关命令

命令 说明
set 显示当前 Shell 所有变量,/etc/bashrcsshell变量,/etc/profile环境变量,用户环境变量,自定义变量。
env 显示当前用户的环境变量。~/.bashrcs~/.profile
export 显示从 Shell 中导出成环境变量的变量,也能通过它将自定义变量导出为环境变量。但只是临时生效,shell关闭后,变量就会释放。
unset 删除环境变量,执行unset PATH,再执行ls将提示找不到ls命令
  • 用户级别环境变量定义文件:~/.bashrc、``~/.profile
  • 系统级别环境变量定义文件:/etc/bashrc/etc/profile(部分系统为:/etc/bash_profile)、/etc/environment

环境变量名

环境变量名 说明
$PATH 命令的查找路径,和Windows中的PATH差不多。查找顺序时从前往后的顺序。假设有两个名字一样的程序配置在path下,会调用配置在前面的一个。echo $PATH查看当前配置。新编写的程序加入环境变量, PATH=$PATH:/home/用户名/程序名,shell关闭后将会失效
$LANG linux主语系环境变量,例$LANG=zh_CN.UTF-8
$LIBRARY_PATH 编译链接时调用的动态库路径
$LD_LIBRARY_PATH 运行时调用的动态库路径,配置临到的动态库路径

C获取环境变量

extern char ** environ;获取环境变量

environ时一个二级字符指针,相当于一个字符串数组,是程序运行的环境变量,当程序启动时,会复制,父进程的环境变量。程序在shell中运行,父进程就是当前shell。
若当前shell使用了export a=123,程序运行后environ也会存在a=123

#include <stdio.h>
extern char ** environ;//本程序的环境变量
int main(int argc, char * argv[])
{
    int count = 0;
    while (environ[count])
    {
        puts(environ[count]);
        ++count;
    }
    printf("总行数=%d\n", count);
}

getenvsetenvunsetenv函数

getenvsetenvunsetenv函数三个函数存在stdlib.h中。
char *getenv (const char *__name)
根据环境变量名获取环境变量
int setenv (const char *__name, const char *__value, int __replace)
设置环境变量,replace=0表示若存在不进行替换,replace=1表示若存在也会进行替换。
int unsetenv (const char *__name)
根据环境变量名删除环境变量

#include <stdio.h>
#include <stdlib.h>
int  main(int argc, char * argv[])
{
    char * lang = getenv("LANG"); // 获取本程序运行的语言环境
    if (NULL == lang)
    {
        return -1;
    }
    puts(lang);
    char * a = getenv("a");
    if (a == NULL)
    {
        puts("不存在");
        setenv("a", "345", 0);
    }
    else
    {
        puts(a);
        setenv("a", "345", 1); // 第三个参数为1表示存在就替换, 为0表示,存在就算了
    }
    a = getenv("a");
    puts(a);

    unsetenv("a"); // 删除本程序的a的环境变量, 对父进程没有影响
    a = getenv("a");
    if (a == NULL)
    {
        puts("不存在");
    }
    return 0;
}
发布了62 篇原创文章 · 获赞 28 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/native_lee/article/details/105268018
今日推荐