简体   繁体   中英

whether the environment variable exported in c function will be available in parent shell?

I was writing a shell on which i am calling ac 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.

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 (ie the shell).

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

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 (eg 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM