//------------------------------------------------------------------- // tryclone.cpp // // This program illustrates use of the Linux 'clone()' function // to create (1) a separate 'thread' executing within same task // address-space, and (2) another 'thread' that executes within // a copy of the original task's address-space. // // programmer: ALLAN CRUSE // written on: 26 SEP 2004 //------------------------------------------------------------------- #include // for printf() #include // for malloc() #include // for getpid() #include // for clone() #include // for wait() #define STACKSIZE 4096 #define FLAGS1 ( SIGCHLD | CLONE_VM ) #define FLAGS2 SIGCHLD int mythread( void *data ) { int *info = (int*)data; printf( "\nHello from thread (pid=%d)\n", getpid() ); printf( "info=%d (initial) ", info[0] ); info[0] += 1; printf( "info=%d (final) \n", info[0] ); return 0x12345678; } int main( int argc, char **argv ) { int info = 0, status, retval; // local variables // allocate memory for the thread's stack void *thread_stack = malloc( STACKSIZE ); void *tos = (void*)((int)thread_stack + STACKSIZE ); // execute a separate thread within this same address-space retval = clone( mythread, tos, FLAGS1, &info ); wait( &status ); printf( "\nparent (pid=%d) reports retval=%d \n", getpid(), retval ); printf( "status=%08X info=%d \n", status, info ); // execute another thread in a copy of this address-space retval = clone( mythread, tos, FLAGS2, &info ); wait( &status ); printf( "\nparent (pid=%d) reports retval=%d \n", getpid(), retval ); printf( "status=%08X info=%d \n", status, info ); // release the allocated storage-area free( thread_stack ); }