簡單shell實現

來源:互聯網
上載者:User

標籤: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實現

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.