linux 環境變量函數getenv()和putenv()的使用


環境變量相關函數:

getenv()和putenv()

代碼示例【Linux程序設計(4th)_4.2小節配套代碼】:

程序功能:編寫一個程序來打印所選的任意環境變量的值;如果給程序傳遞第二個參數,還設置環境變量的值
//
1 The first few lines after the declaration of main ensure that the program, environ.c, has been called correctly. #include <stdlib.h> #include <stdio.h> #include <string.h> /************************ argc:參數個數(包含程序名) argv:代表參數自身的字符串數組; argv[0]為程序名,argv[1]為第1個實際參數 argv[2]為第2個實際參數 ************************/ int main(int argc, char *argv[]) { char *var, *value; if(argc == 1 || argc > 3) { //確保實際參數只有1個(argc=2)或2個(argc=3) fprintf(stderr,"usage: environ var [value]\n"); exit(1); } // 2 That done, we fetch the value of the variable from the environment, using getenv. var = argv[1]; //第一個實際參數的參數名 value = getenv(var); //第一個實際參數的參數值 if(value) //判斷參數值是否存在 printf("Variable %s has value %s\n", var, value); else printf("Variable %s has no value\n", var); // 3 Next, we check whether the program was called with a second argument. If it was, we set the variable to the value of that argument by constructing a string of the form name=value and then calling putenv. if(argc == 3) { //如果第二個實際參數存在 char *string; value = argv[2]; //獲取第2個參數的值 string = malloc(strlen(var)+strlen(value)+2); //為第二個參數的“參數名=參數值”開辟空間(+2表示“=”和空格) if(!string) { //如果開辟空間失敗 fprintf(stderr,"out of memory\n"); exit(1); } strcpy(string,var); strcat(string,"="); strcat(string,value); printf("Calling putenv with: %s\n",string); if(putenv(string) != 0) { //putenv()成功返回0.若環境變量設置失敗 fprintf(stderr,"putenv failed\n"); free(string); //釋放開辟的內存空間 exit(1); } // 4 Finally, we discover the new value of the variable by calling getenv once again. value = getenv(var); if(value) printf("New value of %s is %s\n", var, value); else printf("New value of %s is null??\n", var); } exit(0); }

 注意:環境僅對程序本身有效。在程序里做的環境變量更改不會反映到外部環境,這是因為變量的值不會從子進程(你的程序)傳播到父進程(shell)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM