//---------------------------------------------------------------- // tryforks.cpp // // This demo program was written in order to explore some // aspects of task scheduling under Linux. It executes a // loop that repeatedly calls the 'fork()' function so as // to create a requested number of child processes. Each // child just prints a brief message, then calls 'exit()' // to terminate itself. Meanwhile, the parent process is // executing a second loop that repeatedly calls 'wait()' // in order to be sure that each child indeed terminates. // It may be interesting to examine the resulting output. // // Compile using: $ make tryforks // Execute using: $ tryforks // // programmer: ALLAN CRUSE // written on: 11 FEB 2003 //---------------------------------------------------------------- #include // for fork(), getpid() #include // for atoi(), exit() #include // for printf() #include // for wait() int main( int argc, char **argv ) { int i, count = 0; // get the command-line argument (and display it) if ( argc > 1 ) count = atoi( argv[1] ); printf( "\nok, the number of children will be %d \n\n", count ); // create the requested number of child processes for (i = 0; i < count; i++) if ( fork() == 0 ) { int pid = getpid(); printf( "I am child #%d (pid=%d)\n", i+1, pid ); exit(0); } // await termination by each of the child processes for (i = 0; i < count; i++) { int status = 0; int pid = wait( &status ); printf( "process %d is finished\n", pid ); } // terminate the parent when no more children are left printf( "\nok, all %d children have died\n\n", count ); exit(0); }