The global variable environ in LinuxC [turn]

The global variable environ in LinuxC [turn]

  • The environ variable in Linux C is a char** type, which stores the environment variables of the system.
  • To traverse environment variables, you can use the following program:
#include <stdio.h>

extern char ** environ;

int main()
{
    char ** envir = environ;
    
    while(*envir)
    {
        fprintf(stdout,"%s",*envir);
        envir++;
    }
    return 0;
}
  • Because environ is a global external variable, remember to declare it with the extern keyword before using it, and then use it.
  • This variable is declared in the unistd.h header file, so unist.h can also be included. At this time, there is no need to extern declaration of environ (it should be declared in unistd.h), the code is as follows:
#include <stdio.h>
#define __USE_GNU
#include <unistd.h>
//extern char ** environ;
int main()
{
    char ** envir = environ;
    
    while(*envir)
    {
        fprintf(stdout,"%s",*envir);
        envir++;
    }
    return 0;
}
  • The problem to be noted is that conditional compilation is used where environ is declared in unistd.h. The condition for compilation is #ifdef __USE_GNU. This macro is not defined by default in LinuxC, so #include <unistd.h> must be added before #include <unistd.h>. define __USE_GNU
  • Another way to traverse environment variables is to use the parameters of the main function. Our common main function takes two parameters int argc and char * argv[], but there is actually a main function with three parameters, as follows:
int main(int argc, char *argv[], char *env[])
{
    int index = 0;
    while(env[index] != NULL)
    {
        printf("env[%d]: %s", index, env[index]);
        ++index;
    } 
    return 0;
}

 

Guess you like

Origin blog.csdn.net/baidu_41388533/article/details/114850073