子进程会影响父进程的环境? [英] Can the child process affect parent process' environment?
问题描述
什么是的孩子继承了父母的环境的是什么意思?通过复制整个环境继承,或通过接收指向同一个环境中继承(不知)?
What does "the child inherits the parent's environment" mean? Inherits by copying the whole environment, or inherits by receiving pointer to the same environment (somehow)?
下面是我的情况:
- 我有一个正在运行的进程
P
与它自己的环境(变量) - 在某些时候,
P
执行叉
- 在
0
的if语句
(又名子进程中的C
)的execv
执行 - 这两个进程将继续独立运行。
- I have a running process
P
with its own environment (variables) - At some point,
P
executesfork
- In the
0
-clone of theif-statement
(a.k.a. in the child processC
), anexecv
is executed - Both processes continue running independently.
所以,在有些时候,应用程序停止正常工作。其原因是 - 破的环境。
So, in some moment, the application stops working fine. And the reason is - "broken" environment.
有趣的是,这两个环境有所改变。当我开始父进程和执行
The interesting part is, that both environments are changed.. When I start the parent process and execute
$ cat /proc/PID/environ
为 - 家长和过程,一切都很好。几小时后,应用程序停止工作,当我执行上面再行(检查环境),两者都改变,大量的环境变量的缺失 - 只有标准的是有(如 PWD
,首页
, USER
,等等)。
这怎么可能?并在可能的问题 - 在儿童或父
How is this possible? And where could the the problem - in the child or in the parent?
的 修改 的感谢所有的答案,从+1我,因为他们是正确的(@caf,@Saphrosit和@R ..)。这样做的原因问题真的很傻。
Thanks all for the answers, +1 from me, as they were all correct ( @caf, @Saphrosit and @R..). The reason for this issue is really silly..
所有的环境变量放在 / etc / profile文件
这是登录后(即..我不知道)执行。
All environment variables were placed in /etc/profile
which is executed AFTER LOGIN (that.. I didn't know).
那么,它的出现,这个问题发生在机器的重新启动。因此,在启动时,应用程序将再次启动,但 / etc / profile文件/
是不会执行/读取。这会导致不良行为。这就是为什么这个问题上手动重启消失 - 一旦根
已登录(通过 SSH
),环境变量从的/ etc /型材
被读取,当父进程重新启动(由根
),这一切都很好 - 环境变量继承。
Well, it appeared, that the issue have happened on restart of the machine. So, on start-up, the application is started again, but /etc/profile/
is not executed/read. And this causes the bad behavior. And that's why the problem disappears on manual restart - once a root
is logged in (through ssh
), the environment variables from /etc/profiles
are read, and when the parent process is restarted (by root
), it's all fine - the environment variables are inherited.
愚蠢的错误。
推荐答案
这孩子在叉的瞬间继承父的环境的副本()
。在任一过程中对环境的后续变化不影响其他
The child inherits a copy of the parent's environment at the moment of the fork()
. Subsequent changes to the environment in either process do not affect the other.
您可以改变这一点的唯一方法是做一些很奇怪的,像放置在 MAP_SHARED
区域环境,或者使用 ptrace的()
。你知道,如果你做了这样的事情,虽然。
The only way you could alter this is by doing something very strange, like placing the environment in a MAP_SHARED
area, or using ptrace()
. You'd know it if you did something like this, though.
这篇关于子进程会影响父进程的环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!