Putenv() & Getenv() Bug ?

uunet!bria!mike uunet!bria!mike
Sat Feb 16 13:25:54 AEST 1991


In an article, KING.ICO.OLIVETTI.COM!borzieri (Ivan Borzieri) writes:
>I wrote two c modules called by a fortran main.
>in the first  c module I call the system function "putenv()" which should
>set a variable in the environment.
>In the second  c module I call the system function "getenv()" to read 
>the value of the previous set variable.
>The value returned by getenv() is NULL, id est, that variable
>doesn't exist.
>Now my question is : is this right ?

I have found putenv() to be particuarly annoying, and wonderfully inconsistent
in implementation.  For example, not all putenv()'s guarantee that the
newly created variable is inherited by child processes.

Try this ditty to see if your putenv() is broken:

#include <stdio.h>

main()
{
	putenv("FOO=BAR");
	printf("FOO=%s\n",(char *)getenv("FOO"));

	if ( fork() )
		wait(NULL);
	else
		execlp("/bin/sh","/bin/sh",NULL);
}

When you run this program, you should see "FOO=BAR" and then a shell
prompt; type "echo $FOO" and you should get "BAR".  Press CTRL-D to jump
out of the subshell.  If you don't get this kind of response, I would
consider your putenv() broken.

If it is broken, then write some subroutines to handle the environment
yourself (_environ is a pointer to an array of pointers to char's that
is the current environment).  Use execle() or execve() to pass your own
table to a child process.  If you need more specific information on
doing this type of thing, send me mail, and I'll help.

>I know that in C-Shell scripts, when you set variables you loose them
>as you exit the script.
>Is it the same or this is a operating system bug ?

Neither.  Is is a "problem" with the way that the putenv() and getenv()
subroutines are implemented.  Shell variables are "lost" because scripts
are executed in subshells. 

Golden rule:  No child process may modify its parent's environment.

Hope this helps.
-- 
Michael Stefanik, MGI Inc., Los Angeles| Opinions stated are not even my own.
Title of the week: Systems Engineer    | UUCP: ...!uunet!bria!mike
-------------------------------------------------------------------------------
Remember folks: If you can't flame MS-DOS, then what _can_ you flame?



More information about the Comp.unix.wizards mailing list