0

I was writing a shell on which i am calling a c function where i exports a variable. In below example

my_test.c
int main()
{
   setenv("MY_NAME","kk_rathor",1);
   // get and print MY_NAME works here 
}

my_test_Sh.sh  
#!bin/sh
test
echo $MY_NAME // does not works here 

I am getting not getting my name on printing $MY_NAME However if i am exporting anything in shell i can get it on test.c.

Is the scope of variable exported from test.c is only in that function only. if not then what am i doing wrong ?

Thanks Please let me know if the question is not clear.

krishnakant
  • 355
  • 1
  • 4
  • 17

2 Answers2

2

Environment variables are local to the current process, and are propagated (=copied) to child processes on creation. When you set MY_NAME in the C program it gets set just in its process, it cannot be propagated to the parent (i.e. the shell).

If you want to provide some data to the shell, write it on standard output.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • Thanks.. It wasn't clear to me whether my C program varible will be propagated to the parent. – krishnakant Nov 02 '17 at 06:26
  • About writing the data to the standard output. Can you please elaborate or provide me the direction where i can proceed. – krishnakant Nov 02 '17 at 06:29
  • Nothing fancy - just print to standard output using `printf` and the like and capture the output using `$(...)`. But probably this is not what you want, you should clarify better what you are trying to achieve. – Matteo Italia Nov 02 '17 at 06:44
  • How can i capture the output in the shell ? I have updated the question head. Will it serve my purpose ? – krishnakant Nov 02 '17 at 09:38
2

Read about getenv(3) and setenv(3) and putenv(3)

But environment variables (actually, the entire virtual address space and process state) are local to their process (e.g. your shell) and changing it does not affect those in other processes (except future child processes obtained with fork(2)). Hence changing an environment variable -or any other memory location, or the working directory, or file descriptors, etc...- in a child process don't affect its parent process (or any other existing one). See also fork(2) and execve(2).

You should consider other kinds of inter-process communication such as pipe(7)-s or socket(7)-s (and perhaps shm_overview(7) with sem_overview(7)). You might want to have some event loop above poll(2).

Read intro(2), syscalls(2) and some book like ALP.

BTW, most existing Unix shells are free software. So you can download and study their source code. And you could strace(1) them. See also this.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547