//---------------------------------------------------------------- // myshell.cpp // // Here is the skeleton for a 'shell' application-program. // // programmer: ALLAN CRUSE // written on: 08 SEP 2004 // revised on: 22 SEP 2004 -- child keeps parent environment //---------------------------------------------------------------- #include // for printf(), perror() #include // for read(), write(), fork(), execve() #include // for exit() #include // for strtok() #include // for wait() int main( void ) { for(;;) { // display this shell's command-prompt char prompt[] = "\nmyshell $ "; write( 1, prompt, sizeof( prompt ) ); // accept the user's command-line char command[ 256 ] = { 0 }; int nbytes = read( 0, command, sizeof( command ) ); if ( nbytes < 0 ) { perror( "myshell" ); continue; } // parse the user's command-line int argc = 0; char *argv[ 64 ]; argv[ argc ] = strtok( command, " \t\n" ); while ( ++argc < 64 ) if ( !(argv[ argc ] = strtok( NULL, " \t\n" )) ) break; // fork a child-process int pid = fork(); if ( pid == 0 ) // child process { // try to execute the user's command if ( execv( argv[ 0 ], argv ) < 0 ) //<---- 9/22/2004 printf( "myshell: bad command\n" ); exit(0); } // parent-process waits for child-process to exit int status = 0; wait( &status ); } }