0

I am learning fork:

   fork() creates a new process by duplicating the calling process.  The
   new process is referred to as the child process.  The calling process
   is referred to as the parent process.

   The child process and the parent process run in separate memory
   spaces.  At the time of fork() both memory spaces have the same
   content.  Memory writes, file mappings (mmap(2)), and unmappings
   (munmap(2)) performed by one of the processes do not affect the
   other.

The child is an exact duplicate of the parent process.

However, when it comes to bash

[root@iz2ze9wve43n2nyuvmsfx5z ~]# a=3
[root@iz2ze9wve43n2nyuvmsfx5z ~]# bash
[root@iz2ze9wve43n2nyuvmsfx5z ~]# echo $a

[root@iz2ze9wve43n2nyuvmsfx5z ~]# ps --forest
  PID TTY          TIME CMD
32621 pts/1    00:00:00 bash
32644 pts/1    00:00:00  \_ bash
32675 pts/1    00:00:00      \_ ps

Why the child bash not inherit the parent content directly.

I assume it should also be implemented with a fork underlying.

but it inherit the variables for parent have to use export.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 1
    When you run `bash` as a command, that's not just a fork, it's a `fork()` followed by an `execve()`. That starts a whole new process, so it only inherits environment variables, not regular shell variables. – Charles Duffy Nov 15 '18 at 05:10
  • If you want to start a *subshell* and not a *child process*, use `(echo $a)` to do that; everything inside the parens runs in a new, `fork()`ed-off shell (don't use `$$` to check the shell's identity; instead, use `$BASHPID` -- see https://stackoverflow.com/questions/7858191 for explanation). – Charles Duffy Nov 15 '18 at 05:11

0 Answers0