Chapter 6
I sort of lied, command line arguments (last set of notes) are from chapter 6.
We will not cover this chapter in full
If you are in OS or care about memory, you should read it in full.
Otherwise read 6.1, 6.2, 6.6 and 6.7
Discuss
pid_t getpid(void);
pid_t getppid(void);
Both need sys/types.h
Both need unistd.h
Neither can fail
The Environment.
This is a global set of variables that the shell maintains.
Later when we see the
exec
family we will see that this is built into the system.
You normally get your environment from your parent, but this is not a requirement.
These variables control the behavior of programs.
You can see environment variables with
printenv
Setting an environment variable in bash
varname=value
for the current shell only
export varname=value
for all children
Set the value in appropriate init file
See
man bash
on your system
Usually .bashrc, .bash_login
In a bash script
echo $VARNAME
Some special environment variables
$HOME is your home directory
$PATH is your executable path.
This lists where bash searches for programs to execute
The order given is the order searched.
whereis
uses this to find where programs are
It is part of the exec family
If you add . to your path you don't have to type ./ any longer.
But be careful.
$MANPATH
There are some special variables in bash
see
the GUN Bash
document.
PS1 is the prompt
You can change it to be
many things
.
From a c/c++ program
All code in
myenv.C
Old standard: int main(int argc, char * argv[], char * envp[])
This is a null terminated list
for (int i=0; envp[i] != nullptr; i++) { cout << envp[i] << endl; }
The entries will be in the form
varname=value
Note, this is fixed at invocation
Variables added will not be present.
A global variable
extern char ** environ;
Null terminated list as well.
This is dynamic, as the environment changes, so will environ
see
man 7 environ
Setting this to nullptr wipes out the environment.
With library functions
getenv
Needs stdlib.h
char *getenv(const char *name);
Returns a pointer or nullptr
You really should not change the value pointed to.
getenv will return nullptr on fail, but no error code.
setenv
stdlib.h as well.
int setenv(const char *name, const char *value, int overwrite);
If not set, sets it
If set, sets it if overwrite is not 0
This can fail with error codes.
The name can not contain a =
The name can not be null.
The name can not have a lenght of 0.
This allocates memory and copies the string.
unsetenv
int unsetenv(const char *name);
Error for bad variable names.
But not for an attempt to unset something that does not exist.
clearenv
int clearenv(void);
Wipes it out.
There is a
putenv
but I would avoid that.
Environment variables are used to control programs on a long term basis
Usually there is a default value if nothing is set.
Check a global configuration file for a value
Check a local configuration file for a value
Then check the environment for a variable
Finally check command line arguments.