Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Changing Unix environment within a C program

Status
Not open for further replies.

akn846

Technical User
Oct 16, 2001
51
GB
I am trying to port a Korn shell program across to C on a Unix platform.

As part of this program, I need to be able to change the working directory within the C program. I have found the getenv/putenv functions according to the Wrox Beginning Linix programming book.

Whilst I understand that any changes to the Unix environment made within the code will not be seen by the calling Unix process, I have included a call to the system function in order to get the (intended to be the changed) directory - but this program just reports the same directory as when the program started?

Can someone explain what I am doing wrong/or mis understanding.

Below appears the code in question:

#include <stddef.h>
#include <stdlib.h>

extern char **environ;

main (int argc, char *argv[])
{

int RCODE;

RCODE=putenv(&quot;PWD=/tmp&quot;);
system(&quot;pwd&quot;);
if (RCODE != 0)
return (-1);
else
return 0;
}
Thanks

Andy
 
system call execs a new shell, with its own environment. It's like a new login, it reads .profile file.
 
Kenrae

Thanks for this - I did know this, honest!, but having got so excited about learning about putenv/getenv I obviously forgot about it!

Whats the best code I can use to prove that the environment is being changed then?

Regards

Andy
 
How about a getenv() and writing it to stdout?
You can always execute a pwd using exec call. Like:
Code:
execl(&quot;pwd&quot;,&quot;pwd&quot;,0);
 
Thanks again - redirect getenv to stdout?! Please!!!!
 
Where do you see the word &quot;redirection&quot;?
I thought on something like that:
Code:
st=getenv(&quot;PWD&quot;);
write(stdout,st,strlen(st));
 
Oh, and another thing. It's
Code:
execl(&quot;/bin/pwd&quot;,&quot;pwd&quot;,0);
 
Ken

Thanks - but when I use the command about for writing out the information - stdout is not defined on the Dynix system.

Also, I used the execl command you provided above - but the directory reported is the same one as before the program started - whereas I would expect it to be reporting the /tmp directory.

Cheers
 
If stdout is not defined, include stdio.h or write to 1.

It seems that exec calls don't inherit your environ. Try man exec, there should be a way to do it.
 
Ken

Thanks for all your help, changing the stdout to 1 worked a treat!

Thanks again

andy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top