2014-11-04 122 views
1

我是C編程語言的新手,我正在嘗試做一個我自己設定的練習。閱讀用戶命令並執行它

我想要做的是能夠讀入用戶寫入然後執行的命令。我還沒有爲此編寫任何代碼,我真的不確定如何去做。

這基本上是什麼,我想要做:

顯示用戶提示(用於用戶輸入的命令例如/ bin中/ LS -al) 讀取並處理所述用戶輸入

我我目前正在使用MINIX來嘗試創建並更改操作系統。

感謝

+0

請指定您的問題併發布您已經嘗試過的內容。聽起來你想爲MINIX開發一個shell?所以你需要printf,scanf,fork和execve。 – 2014-11-04 15:18:34

+0

是的,我確實想爲MINIX開發一個shell。我想嘗試使用其中一個函數:getline,getdelim和strtok。我目前還沒有嘗試過任何操作,因爲我不確定如何操作 – user3411748 2014-11-04 15:25:17

+0

我只是想從某種指南開始,以及如何從getline函數開始 – user3411748 2014-11-04 15:32:59

回答

0

Shell在新進程中執行命令。這就是它是如何工作的一般:

while(1) { 
    // print shell prompt 
    printf("%s", "@> "); 
    // read user command - you can use scanf, fgets or whatever you want 
    fgets(buffer, 80, stdin); 
    // create a new process - the command is executed in the new child process 
    pid = fork(); 
    if (pid == 0) { 
     // child process 
     // parse buffer and execute the command using execve 
     execv(...); 
    } else if (pid > 0) { 
     // parent process 
     // wait until child has finished 
    } else { 
     // error 
    } 
} 
+0

我將如何使用getline函數的這個過程?我是否會將fgets改爲getline? – user3411748 2014-11-04 15:48:40

+0

是的,你可以使用'getline'而不是'fgets'。 – 2014-11-04 15:52:28

0

這是我的代碼至今:

包括

int main(void) { 
    char *line = NULL; 
    size_t linecap = 0; 
    ssize_t linelen;  

    while ((linelen = getline(&line, &linecap, stdin)) > 0){ 
     printf("%s\n", line); 
    } 

}

這顯然會繼續執行,並打印出一條線直到我按下CTRL-D。我會用什麼樣的代碼來執行用戶輸入的命令?