setenv from c

der Mouse mouse at mcgill-vision.UUCP
Mon Sep 23 12:11:30 AEST 1985


> Is it possible to set a csh environment variable within a C program? I know
> about getenv(), but have failed at attempts to set an environment variable
> from a C program. Basically, what I want to do is "source" a new environment
> variable for the current csh process. Any comments or suggestions would be
> appreciated. Thanks.

     In general, this  is possible theoretically (most UNIX systems) but
impossible in practice.  Now before you get disheartened, note that with
a little cooperation  from the shell this is quite feasible.   There are
at least two ways:

(1) If the  program  doesn't want to  print anything, have it just print
the  command  the shell should execute and then  use  backquotes  in the
shell  to catch this.  Then  you can "eval" it (you did say  csh, didn't
you...yes).

(2) If the program wants to  do printing, have  it write a file on  /tmp
somewhere  (eg, use  getppid() to  find the parent shell's  PID and  use
that) that the shell can find (in  the  example, /tmp/$$ or some  such).
Then  the  "command"  users  see is  actually an  alias which  runs  the
program, sources the temp file, and removes it.  Something like that.

     If you aren't interested in hairy reasons or explanations, you  can
stop reading now.

     The reason for this is  that  there is  no way provided  for  the C
program to  do anything  to its  parent  process, such as  modifying the
environment stored  there.   The reason it's possible  theoretically  is
that (theory  only,  note) the C  program can  go  poking around  in the
kernel tables (via /dev/kmem or equivalent) and find out where the shell
process lives  (in memory  or  on  swap)  and  modify it  directly  (via
/dev/mem or /dev/drum or equivalent).  This requires more privilege than
user programs usually have in the first place and it would be difficult,
if not impossible,  to avoid timing  problems  (it's on swap,  ok, clock
ticks and it's in memory, but we still think it's on swap).

     I've  tried to redirect followups  to net.unix (hope it works, this
is the first time I've tried to do that).
-- 
					der Mouse

{ihnp4,decvax,akgua,etc}!utcsri!mcgill-vision!mouse
philabs!micomvax!musocs!mcgill-vision!mouse

Hacker: One responsible for destroying /
Wizard: One responsible for recovering it afterward



More information about the Comp.lang.c mailing list