我愛抄程式碼-程序
阿新 • • 發佈:2022-04-19
一、展示程序的環境變數列表
/* display_env.c 展示程序的環境變數列表. */ #include "tlpi_hdr.h" extern char **environ; /* Or define _GNU_SOURCE to get it from <unistd.h> */ int main(int argc, char *argv[]) { char **ep; for (ep = environ; *ep != NULL; ep++) puts(*ep); exit(EXIT_SUCCESS); }
二、執行時修改環境變數
執行案例:
./modify_env"GREET=Hello" SHELL=/bin/bash BYE=ciao
輸出:
GREET=Hello
SHELL=/bin/bash
執行案例:
./modify_env SHELL=/bin/bash BYE=byebye
輸出:
SHELL=/bin/bash
GREET=Hello world
modify_env.c
/* modify_env.c 本檔案中的程式碼只能在linux環境執行 */ #define _GNU_SOURCE /* Get various declarations from <stdlib.h> */ #include<stdlib.h> #include "tlpi_hdr.h" extern char **environ; int main(int argc, char *argv[]) { int j; char **ep; clearenv(); /* 清空所有環境變數 */ /* 將命令列引數的變數加入env */ for (j = 1; j < argc; j++) if (putenv(argv[j]) != 0) errExit("putenv: %s", argv[j]);/* 如果GREET對應的env變數不存在,則賦值為hello world */ if (setenv("GREET", "Hello world", 0) == -1) errExit("setenv"); /* 刪除BYE對應的env */ unsetenv("BYE"); /* Display current environment */ for (ep = environ; *ep != NULL; ep++) puts(*ep); exit(EXIT_SUCCESS); }
三、跨函式跳轉
goto可以在函式內跳轉,下面的程式碼可以跨函式跳轉
/* longjmp.c 展示通過 setjmp()和longjmp()實現跨越函式的跳轉. 屬於奇淫巧技的範疇,儘量不要使用 使用案例: longjmp longjmp x longjmp x y */ #include <setjmp.h> #include "tlpi_hdr.h" //setjmp、longjmp必須使用同一env,所以設為全域性變數 static jmp_buf env; static void f3(void) { longjmp(env, 3); } static void f2(void) { longjmp(env, 2); } static void f1(int argc) { if (argc == 1) longjmp(env, 1); if (argc == 2) f2(); if (argc == 3) { f3(); } } int main(int argc, char *argv[]) { //setjmp()呼叫為後續的longjmp()呼叫執行的跳轉確立了跳轉目標,該目標正是程式發起setjmp()呼叫的位置 switch (setjmp(env)) { case 0: /* setjmp第一次執行返回0,第二次執行時返回由longjmp設定的val值 */ printf("Calling f1() after initial setjmp()\n"); f1(argc); /* Never returns... */ break; /* ... but this is good form */ case 1: printf("We jumped back from f1()\n"); break; case 2: printf("We jumped back from f2()\n"); break; case 3: printf("We jumped back from f3()\n"); break; } exit(EXIT_SUCCESS); }