Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)?


Here's my scenario:

  1. I have a running process P with its own environment (variables)
  2. At some point, P executes fork
  3. In the 0-clone of the if-statement (a.k.a. in the child process C), an execv is executed
  4. 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

for both - the parent and the process, everything is fine. Some hours later, the app stops working and when I execute the line above again (to check the environment), both are changed and a lot of environment variables are missing - only the standard ones are there (like PWD, HOME, USER, etc.).

How is this possible? And where could the the problem - in the child or in the parent?


EDIT: 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..

All environment variables were placed in /etc/profile which is executed AFTER LOGIN (that.. I didn't know).

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.

Stupid mistake.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
243 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...