2

Is it possible to simulate the behaviour of vfrok with clone? So far I have

pid=clone(fn,cStack,SIGCHLD|CLONE_FS | CLONE_FILES | CLONE_VM | CLONE_VFORK,NULL);

but I still need to pass my own stack, so the new process is working in different stack frame but in the same address space (because of CLONE_VM), and as I understand, if I invoke vfork and don't use some function from exec, the new process is operating in the same address space as the parent, and it uses the same stack frame.

So is it possible to make a new process with clone that operates in the same address space and is using the same stack frame as the parent?

Andna
  • 6,539
  • 13
  • 71
  • 120

1 Answers1

3

It's not possible without writing the function in assembler. This is a fundamental issue that cannot be "fixed"; even the vfork syscall wrapper itself must be written in assembly rather than C for most archs (any arch where the return address is stored on the stack). This is because after the child runs using the same stack as the parent, it will potentially have overwritten the return address that the function (vfork, clone, or some other wrapper) needs to return to in the parent.

In assembler, you simply save the return address in a register before making the syscall.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • +1 for pointing out the stack intricacies. But why is the manual very casual in stating that `vfork() is a special case of clone(2)`?? This seems to indicate that `vfork` _can_ be implemented with `clone`? – Pavan Manjunath Apr 06 '12 at 13:03
  • It can easily be implemented with the `clone` *syscall*. But you cannot wrap C function calls like this when you intend to share the stack. You have to write the `clone`-based version of `vfork` in asm. – R.. GitHub STOP HELPING ICE Apr 06 '12 at 13:04
  • So if I understand correctly, the closest to the vfork I can get with the clone function is the call I written in my first post? I got the same memory space, stopping the parent until child exits, sharing file descriptor table and the same file system info, but they don't share the stack like in vfork? – Andna Apr 06 '12 at 14:01
  • 1
    Yes, that's correct. Personally I'd consider your version better. I find the "return twice" idiom of `fork` and `vfork` to be ugly and error-prone; starting a new function (on a new stack) in the child process is a lot cleaner. – R.. GitHub STOP HELPING ICE Apr 06 '12 at 14:34
  • Interestingly, this technique requires a difference between system calls and regular function calling conventions: the kernel must preserve the value of at least one register that is normally caller-saved. – jilles Apr 07 '12 at 13:56
  • System calls normally preserve all registers except the register the syscall number is loaded into (which is overwritten with the return value). – R.. GitHub STOP HELPING ICE Apr 07 '12 at 20:36