http://blog.csdn.net/lishuhuakai/article/details/11928055
#include <stdio.h>#include<unistd.h>#include<wait.h>#defineMAXLINE 80voidSetup (CharInputbuffer[],Char*argv[]) { intI, J; Char*p; I=0; for(p = inputbuffer;;p + +)/*Splits the character command for a period of time, such as entering ls-l, argv[0]= "ls", argv[1]= "-L", Argv[2]=null*/{argv[i++] =p; while(*p! =' '&& *p! =' /') P++; if(*p = =' /') { Break; } *p =' /'; } Argv[i]= NULL;/*The last parameter must be terminated with null pointer nulls*/EXECVP (argv[0], argv);/*execute command, Argv[0] put the executed command, the rest of the argv put the parameters*/}intMain () {CharInputbuffer[maxline]; Char*argv[maxline/2-1]; while(1) {printf ("command->"); Gets (InputBuffer);/*input Command*/Setup (InputBuffer, argv); printf ("Flutter Street! "); } return 0;}
#include <stdio.h>#include<unistd.h>//#define SIZE#defineMAXLINE 80Char*p;voidSetup (CharInputbuffer[],Char*argv[]) { intI, J; I=0; for(p = inputbuffer;;p + +)/*separate the input characters one by one*/{argv[i++] =p; while(*p! =' '&& *p! =' /') P++; if(*p = =' /') { Break; } *p =' /'; } Argv[i]=NULL; pid_t PID PID= Fork ();/*Create a new child process*/ if(PID = =0)/*for child processes, execute the input command*/{EXECVP (argv[0], argv); printf ("Command not found\n");/*if the EXECVP execution fails, it returns 1, which means the sentence will be executed .*/ } Else if(PID >0)/*for the parent process, wait for*/{Wait (NULL);/*The parent process waits for the child process to finish executing*/ } Else /*Otherwise, it's a mistake.*/{printf ("Fork error\n"); }}intMain () {CharInputbuffer[maxline]; Char*argv[maxline/2-1]; while(1) {printf ("command->"); Gets (InputBuffer); /*about scanf and gets,scanf encountered a space or carriage return for the input character, and gets is accepted for the input space*/Setup (InputBuffer, argv); } return 0;}
Simple shell implementation