Saturday, July 2, 2011

Does the clone() system call ultimately rely on fork functionality?

The critical difference is that fork creates a new address space, while clone optionally shares the address space between the parent and child, as well as file handles and so forth.



Actually, at the conceptual level, the Linux kernel doesn't know anything about processes or threads, it only knows about "tasks".

A Linux task can be a process, a thread or something in between. (Incidentally, this means that the strange children that vfork() creates fit perfectly well into the Linux "task" paradigm).

Now, tasks can share several things, see all the CLONE_* flags in the manpage for clone(2). (Not all these flags can be described as sharing, some specify more complex behaviours).

Or new tasks can choose to have their own copies of the respective resources. And since 2.6.16, they can do so after having been started, see unshare(2).

For instance, the only difference between a vfork() and a fork() call, is that vfork() has CLONE_VM and CLONE_VFORK set. CLONE_VM makes it share its parent's memory (the same way threads share memory), while CLONE_VFORK makes the parent block until the child releases its memory mappings (by calling execve() or _exit()).

Note that Linux is not the only OS to generalize processes and threads in this manner. Plan 9 has rfork().


fork()-->C_lib-->sys_fork()-->do_fork()

vfork()-->C_lib-->sys_vfork()-->do_fork()

clone()-->C_lib-->sys_clone()-->do_fork()

No comments:

Post a Comment