When implementing CGI programs, we sometimes use setenv to set environment variables and pass them to sub-processes. How is the parent process passed to the child process?
[Cpp]
// Father. c
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <unistd. h>
# Include <sys/types. h>
Extern char ** environ;
Int main ()
{
Char * str = "Hello From Father ";
Char * emptylist [] = {NULL ,};
Char * filename = "./child ";
If (fork () = 0)
{
Setenv ("QUERY_STRING", str, 1 );
If (execve (filename, emptylist, environ) <0)
{
Printf ("Execve error ");
}
}
Wait (NULL );
Return 0;
}
[Cpp]
// Child. c
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
Int main ()
{
Printf ("this is in son process \ n ");
Char * p2 = (char *) getenv ("QUERY_STRING ");
If (p2)
Printf ("% s \ n", p2 );
Return 0;
}
Extern char ** environ
This statement points to a string array of environment variables.
The global variable environ defined in libc points to the environment variable table. environ is not included in any header file, so it must be declared with extern during use. If no extern exists, the environment variables cannot be obtained in the child process. The following is an example of how environ gets environment variables:
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <unistd. h>
# Include <sys/types. h>
Extern char ** environ;
Int main ()
{
Char ** p = environ;
While (* p! = NULL)
{
Printf ("% s (% p) \ n", * p, * p );
* P ++;
}
Return 0;
}
In addition, it should be noted that the environment variables cannot be set at will when setenv is set. For example, if you want to set holo = "hello", this cannot be done. Why? When fork is called to generate a child process, the child process will make a copy of the environment variable of the parent process, because as mentioned above, the copy is implemented through environ, and environ is already defined. If you do not want to use setenv to pass environment variables, you can only use the system environment variables as temporary exchanges for transmission.
Author: firefoxbug