[英]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. 我正在编写一个外壳程序,在该外壳程序上我调用ac函数,并在其中导出变量。 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. 我在打印$ MY_NAME时得不到我的名字,但是如果我在shell中导出任何内容,我可以在test.c上得到它。
Is the scope of variable exported from test.c is only in that function only. 从test.c导出的变量的作用域仅在该函数中。 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). 当您在C程序中设置
MY_NAME
,仅在其过程中对其进行了设置,因此无法将其传播到父级(即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) 阅读有关getenv(3)和setenv(3)和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) ). 但是环境变量(实际上,整个虚拟地址空间和进程状态)对于它们的进程是本地的(例如,您的Shell),并且对其进行更改不会影响其他进程中的变量(除了通过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) .
另请参见fork(2)和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) ). 你应该考虑其它类型的进程间通信 ,如管道(7) -s或插座(7) -S(也许shm_overview(7)与sem_overview(7) )。 You might want to have some event loop above poll(2) .
您可能希望在poll(2)之上有一些事件循环 。
Read intro(2) , syscalls(2) and some book like ALP . 阅读intro(2) , syscalls(2)和ALP之类的书。
BTW, most existing Unix shells are free software . 顺便说一句,大多数现有的Unix shell是免费软件 。 So you can download and study their source code.
因此,您可以下载并研究其源代码。 And you could strace(1) them.
您可以strace(1)他们。 See also this .
另请参见本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.