標籤:else 失敗 實現 details 參數 ret csdn 指標 tail
http://blog.csdn.net/lishuhuakai/article/details/11928055
#include <stdio.h>#include <unistd.h>#include <wait.h>#define MAXLINE 80void setup (char inputBuffer[], char *argv[]){ int i, j; char *p; i = 0; for (p = inputBuffer; ;p++)/*將字元命令一段一段拆分開來,如輸入ls -l,則argv[0]= "ls",argv[1]="-l",argv[2]=NULL*/ { argv[i++] = p; while (*p != ‘ ‘ && *p != ‘\0‘) p++; if (*p == ‘\0‘) { break; } *p = ‘\0‘; } argv[i] = NULL;/*最後一個參數須用null 指標NULL作結束*/ execvp (argv[0], argv);/*執行命令,argv[0]放著執行的命令,其餘的argv放著參數*/}int main(){ char inputBuffer[MAXLINE]; char *argv[MAXLINE / 2 - 1]; while (1) { printf ("COMMAND->"); gets (inputBuffer);/*輸入命令*/ setup (inputBuffer, argv); printf ("撲街!"); } return 0;}
#include <stdio.h>#include <unistd.h>//#define SIZE 20#define MAXLINE 80char *p;void setup (char inputBuffer[], char *argv[]){ int i, j; i = 0; for (p = inputBuffer; ;p++)/*一個一個地將輸入字元分開*/ { argv[i++] = p; while (*p != ‘ ‘ && *p != ‘\0‘) p++; if (*p == ‘\0‘) { break; } *p = ‘\0‘; } argv[i] = NULL; pid_t pid pid = fork();/*建立一個子進程*/ if (pid == 0)/*對於子進程,執行輸入的命令*/ { execvp (argv[0], argv); printf ("command not found\n");/*如果execvp執行失敗的話,會返回-1,也就是這句話會被執行*/ } else if( pid > 0 )/*對於父進程,等待*/ { wait(NULL);/*父進程等待子進程執行完*/ } else /*否則的話,就出錯了*/ { printf ("fork error\n"); }}int main(){ char inputBuffer[MAXLINE]; char *argv[MAXLINE / 2 - 1]; while (1) { printf ("COMMAND->"); gets (inputBuffer); /*關於scanf和gets,scanf對於輸入的字元遇到空格或斷行符號就結束了,而gets對於輸入的空格也接受*/ setup (inputBuffer, argv); } return 0;}
簡單shell實現