Search code examples
linux-kernelclonesystem-calls

child stack explaination in clone system call


in clone (2) man page, for child stack its mentioned that

Since the child and calling process may share memory, it is not possible for the child 
process to execute in the same stack as the calling process.

can anybody please explain how "sharing memory" ,specifically, makes it impossible. OTOH, a common perception is that the function execution sequence in a thread will be different from others, so we need another stack there.

Thanks, Kapil


Solution

  • Two threads can't use the same stack. They'd just mess it up for each other, and soon crash.

    When using fork, there's no memory sharing. Both threads have the same value of the stack pointer, but it points to physically different memory pages.

    When using pthread_create, a new stack pointer is chosen for the new thread, separate from the parent. This way they don't corrupt each other's stack.

    clone is a low-level function, which is somewhere between the two. It keeps memory shared, so the threads must not shared the stack. But unlike pthread_create, the new stack pointer is determined by the user, which may choose it as he wishes. The sentence you quote warns that you should choose it with care.