/* * This code is just to give you some familiarity about system programming. * This gives you an insight of how to fork a process and execute UNIX commands from within a C program (Simple Shell) */ #include #include #include #include void parse( char *buffer, char **args); void execute( char **args); main(){ char buffer[1024]; char *args[32]; while( 1 ){ printf("\n->"); if( scanf("%s", buffer) == NULL ){ printf("->"); exit( 0 ); } parse( buffer, args ); execute( args ); } } void parse( char *buffer, char **args ){ while( *buffer != NULL ){ while( (*buffer == ' ') || (*buffer == '\t')) *buffer++ = NULL; *args++ = buffer; while( (*buffer != NULL) && (*buffer != ' ') && (*buffer != '\t')) buffer++; } *args = NULL; } void execute( char **args ){ int pid, status; pid = fork(); switch(pid) { case EAGAIN: perror("Error EAGAIN: "); return; case ENOMEM: perror("Error ENOMEM: "); return; } if( pid == 0 ){ execvp(*args, args); perror(*args); exit(1); } while(wait(&status) != pid); }