2014-10-28 54 views
0

我已經在C中編寫了一個簡單的shell,並且試圖獲取「;」操作員正常工作,這將是用戶鍵入命令1; command2插入命令行,shell執行第一個命令,然後執行第二個命令。但是,似乎無論出於何種原因,它只是執行第二個命令。任何人有一個想法爲什麼?加入運算符「;」在我的shell中工作不正常

這裏是我的代碼特定部分:

char* next = strchr(cmd, ';'); 

while (next != NULL) { 
    /* 'next' points to ';' */ 
    *next = '\0'; 
    input = run(cmd, input, first, 0); 

    cmd = next + 1; 
    next = strchr(cmd, ';'); 
    first = 0; 
} 
+0

可能是'cmd'錯誤(例如它是一個字符串文字) – 2014-10-28 06:18:00

回答

0

這裏strchr()功能分號我後返回字符指針的值。

如果輸入是

​​3210

strchr()返回

; ps 

作爲結果。

使用strtok()而不是strchr(),它用於根據需要分割字符串。

喜歡的東西如下:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(void) 
{ 
    char *str = malloc(20); 
    char *tok = NULL; 


    strcpy(str, "command1;command2"); 
    tok = strtok(str, ";"); 
    while (tok) 
    { 
     printf("Token: %s\n", tok); 
     tok = strtok(NULL, ";"); 
    } 

    free(str); 

    return 0; 
} 

here

0

你的代碼是爲我工作。只是增加了處理角落案件的條件。請檢查下面的代碼。

char* next = strchr(cmd, ';'); 
while (next != NULL) { 
    /* 'next' points to ';' */ 
    *next = '\0'; 
    input = run(cmd, input, first, 0); 
    printf ("%s\n",cmd); 

    cmd = next + 1; 
    next = strchr(cmd, ';'); 

    if (NULL ==next){ 
    input = run(cmd, input, first, 0); 
     printf ("%s\n",cmd); 
    } 
    first = 0; 
} 
+0

謝謝你的回答。我試過你的編輯,但是當我輸入ls; ps進入命令行,它表示分段錯誤,然後執行第二個命令。任何想法爲什麼? – GamerDJX 2014-10-28 06:26:52

+0

我沒有運行api。所以它可能會崩潰。 ls; ps有額外的空間。你可以嘗試像ls; ps – 2014-10-28 06:32:11