Bibek
Bibek

Reputation: 1

Linux Process Creation : User mode stack

I am new to Linux, Understood that from user mode, if a process call the system call fork(), then the process stars executing in system mode and a new child process is created with a new kernel mode space ( it include stack also) is allocated to that newly created child process. My question is, 1>how and when is the user mode stack created for this newly created process? 2>How kernel know where is the user mode stack for this newly created process? 3>Can kernel access the user mode stack while executing in kernel mode in that newly created process context?

correct me if my question or understanding is wrong.

Thanks in advance for the guidance.

regards Bibek

Upvotes: 0

Views: 1186

Answers (3)

MarkR
MarkR

Reputation: 63538

My answers are:

  1. The entire virtual memory is duplicated for the new process, including any stacks. The kernel treats it no differently than any other pages
  2. The kernel doesn't need to know where the user-mode stack is to achieve this, it just duplicates the whole address space.
  3. It does not need to access the user-mode stack to do this.

The only difference is the return value that the kernel gives to the parent and child.

When the fork() system call returns, it will go back to the same address in the parent and child but with a different return value (child always gets 0, parent gets child's pid). As they each have their own copy (it would be copy-on-write, but will get written to very soon) of the stack, this is no problem.

Upvotes: 1

J-16 SDiZ
J-16 SDiZ

Reputation: 26910

  1. Usually, a program get a new user mode stack when you call exec() or create a new tread. If you want to do this manually, use the mmap() syscall. Note: a process can have multiple stack (green threads or signal stack).

  2. When you make a syscall, your register are saved -- this include the stack address.

  3. Most of the kernel function cannot access the user mode stack directly. But, of course, being in ring-0, the kernel can adjust the permission and assess it when it want to. In an unmodified kernel, this is restricted to a few selected function. (search copy_to_user and copy_from_user in your kernel source)

Upvotes: 1

nimrodm
nimrodm

Reputation: 23799

fork() duplicates the entire memory map allocated to the forking processes (the parent). It creates an identical process which then proceeds independently of the parent process.

The two start with identical heap and stack. The x86 register pointing to the current stack position points to the same memory address for both the parent and the child processes (since their memory map is identical).

Upvotes: 4

Related Questions