Tuesday, 9 September 2014

clone() in Linux

clone ():

This library function is used to creates a new process.
Depending on flags passed to this function, It allows the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers.
The main use of clone() is to implement threads where multiple threads of control in a program that run concurrently in a shared memory space.

Fork() also internally calls this function.
 
Prototype is:
int __clone(int (*fn) (void *), void *child_stack, int flags, void *arg)
where
fn: The fn argument is a pointer to a function that is called by new child process at the beginning of its execution. When function “fn” returns, its returnvalue is exit code for child process.

child_stack: It is location of the stack used by the child process.Usually points to the topmost address of the memory space set up for the child stack (As stack grows downward)

flags: The low byte of flags contains the number of the terminationsignal sent to the parent when the child dies.

arg: The arg argument is passed to the fn function.


This function returns
 On success: thread ID of child id returned to context to calling  process. 
 On failure: No child process will be created and appropriately  errno. will be  returned.

 clone () system call leaves all memory management up to the  programmer.  The first thing to be done is allocating space for the  stack of the new child  thread with malloc (). Once this is done,  the clone () call is issued to begin a  new context of execution,  starting at the beginning of the given function.

Raw clone() system call:

long clone(unsigned long flags, void *child_stack,
                      void *ptid, void *ctid,
                      struct pt_regs *regs);

 Here the execution in the child continues from the point of the  call. As such,  the fn and arg arguments of the clone() wrapper  function are omitted.    Furthermore, the argument order changes.

 Another difference for the raw system call is that the child_stack  argument may  be zero, in which case copy-on-write semantics ensure  that the child gets  separate copies of stack pages when either  process modifies the stack.

No comments:

Post a Comment