/* clone1.c++ Creation of new thread by clone() */ #include using namespace std; #include #include #include #include #include #include #include #define MAXSTACK 4096 int fact ; // global data int what(void *p) ; int main() { // clone1.c++ int chPID, status, n ; char *chStack ; cout << "Enter a +ve integer: " ; cin >> n; chStack = (char *) malloc(MAXSTACK); // Memory for new stack chStack = chStack + MAXSTACK; // Stack grows towards lower // address. Bottom of stack chPID = clone(what, chStack, CLONE_VM, (void *)&n) ; // Cloned process will execute // 'what(NULL)'. // CLONE_VM - same memory space // &n is parameter to 'what' // chPID - cloned process id cout << "Inside proc: pid = " << getpid() << "\n" ; cout << "Inside proc: cpid = " << chPID << "\n" ; waitpid(chPID, &status, __WCLONE) ; // __WCLONE - wait for // cloned process cout << "Inside proc:" << n << "! = " << fact << "\n" ; return 0 ; } int what(void *p) { int n = *(int *)p, i; for(fact=i=1;i<=n;++i) fact *= i; return 0 ; }