环境变量是OS运行时指定一些运行时参数,最熟悉的是PATH变量,指明系统命令可执行文件的搜索路径。
root@han-VirtualBox:~# echo $PATH/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
环境变量也常作为C程序调用脚本时的参数传递手段,即在C程序中将参数以环境变量的方式放入,然后调用脚本,这样在脚本中直接获取对应环境变量的值即可。
需要注意的是:环境变量可以被子进程继承,但是不能隔代继承
C中的标准函数,在头文件stdlib.h中定义,主要使用的API简述包括:
(1)获取
原型:
char *getenv(const char *name)
说明:获取参数name环境变量的值
返回值:执行成功返回指向该内容的指针,未找到则返回NULL
示例:
#include <unistd.h>#include <stdlib.h>#include <stdio.h>int main(int argc, char **argv){/* test get */char *path = getenv("PATH");printf("%s\n", path != NULL ? path : "none");return 0;}root@han-VirtualBox:demo# ./a.out/root/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
(2)改变或增加环境变量
原型:
int putenv(const char *string)
说明:用来改变或增加环境变量,参数格式为 name=value,如果该环境变量存在,则变量内容会被参数改变,否则成为新的环境变量
返回值:执行成功则返回0,错误返回-1
#include <unistd.h>#include <stdlib.h>#include <stdio.h>static void print_env(const char *name){char *val = getenv(name);printf("%s=%s\n", name, val != NULL ? val : "none");}int main(int argc, char **argv){int ret;ret = putenv("op=add");printf("ret=%d\n", ret);print_env("op");return 0;}root@han-VirtualBox:demo# ./a.outret=0op=add
(3)修改或增加环境第二种
原型:
int setenv(const char *name, const char *value, int overwrite)
说明:更精细化的控制,参数name为环境变量名,value为设置值,overwrite不为0,当name存在时,则原value被修改,如果为0,则不修改
#include <unistd.h>#include <stdlib.h>#include <stdio.h>static void print_env(const char *name){char *val = getenv(name);printf("%s=%s\n", name, val != NULL ? val : "none");}int main(int argc, char **argv){int ret;ret = putenv("op=add");printf("ret=%d\n", ret);print_env("op");printf("test new\n");ret = setenv("rid", "1", 1);print_env("rid");printf("test overwrite\n");ret = setenv("op", "modify", 1);print_env("op");printf("test not overwrite\n");ret = setenv("op", "del", 0);print_env("op");ret = setenv("mask", "24", 0);print_env("mask");return 0;}root@han-VirtualBox:demo# ./a.outret=0op=addtest newrid=1test overwriteop=modifytest not overwriteop=modifymask=24
(4)C中设置环境变量,调用脚本示例
C中使用popen调用脚本
#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>static void print_env(const char *name){char *val = getenv(name);printf("%s=%s\n", name, val != NULL ? val : "none");}static void run_shell(){const char *path = "/freework/demo/test.sh";FILE *f;char buf[128];memset(buf, 0, 128);f = popen(path, "r");if (f == NULL) {printf("open shell failed\n");return;}fread(buf, sizeof(char), 128, f);pclose(f);printf("%s\n", buf);}int main(int argc, char **argv){int ret;ret = putenv("op=add");printf("ret=%d\n", ret);ret = putenv("rid=1");printf("ret=%d\n", ret);print_env("op");print_env("rid");printf("run to script\n");run_shell();return 0;}
shell:测试脚本
#!/bin/shecho "this is shell"echo "op=$op"echo "rid=$rid"
执行结果
root@han-VirtualBox:demo# ./a.outret=0ret=0op=addrid=1run to scriptthis is shellop=addrid=1
文章转载自han码录,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




