• +91 9723535972
  • info@interviewmaterial.com

Unix Interview Questions and Answers

Question - How can I get/set an environment variable from a program?

Answer - Getting the value of an environment variable is done by using `getenv()'.      #include           char *getenv(const char *name); Setting the value of an environment variable is done by using `putenv()'.      #include           int putenv(char *string); The string passed to putenv must *not* be freed or made invalid, since a pointer to it is kept by `putenv()'.  This means that it must either be a static buffer or allocated off the heap.  The string can be freed if the environment variable is redefined or deleted via another call to `putenv()'. Remember that environment variables are inherited; each process has a separate copy of the environment. As a result, you can't change the value of an environment variable in another process, such as the shell. Suppose you wanted to get the value for the `TERM' environment variable. You would use this code:      char *envvar;           envvar=getenv("TERM");           printf("The value for the environment variable TERM is ");      if(envvar)      {          printf("%s\n",envvar);      }      else      {          printf("not set.\n");      } Now suppose you wanted to create a new environment variable called `MYVAR', with a value of `MYVAL'.  This is how you'd do it.      static char envbuf[256];           sprintf(envbuf,"MYVAR=%s","MYVAL");           if(putenv(envbuf))      {          printf("Sorry, putenv() couldn't find the memory for %s\n",envbuf);       &

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners