2013-05-20 16 views
-2

我注意到最新版本的Advanced Unix Programming下的一個簡單shell程序的下列代碼沒有正確運行,並且編譯時出現了有關比較第12行中的指針和整數的警告:高級Unix編程 - 第1章shell代碼錯誤

#include "apue.h" 
#include <sys/wait.h> 

int 
main(void) 
{ 
    char buf[MAXLINE]; /* from apue.h */ 
    pid_t pid; 
    int  status; 

    printf("%% "); /* print prompt (printf requires %% to print %) */ 
    while (fgets(buf, MAXLINE, stdin) != NULL) { 
     if (buf[strlen(buf) - 1] == "\n") 
      buf[strlen(buf) - 1] = 0; /* replace newline with null */ 

     if ((pid = fork()) < 0) { 
      err_sys("fork error"); 
     } else if (pid == 0) {  /* child */ 
      execlp(buf, buf, (char *)0); 
      err_ret("couldn't execute: %s", buf); 
      exit(127); 
     } 

     /* parent */ 
     if ((pid = waitpid(pid, &status, 0)) < 0) 
      err_sys("waitpid error"); 
     printf("%% "); 
    } 
    exit(0); 
} 

簡單的shell程序會運行,但它會說「沒有這樣的文件或目錄」的程序,我肯定在系統上。

回答

2

的問題是,在下面一行的雙引號:

if (buf[strlen(buf) - 1] == "\n") 

它應該是這樣的:

if (buf[strlen(buf) - 1] == '\n') 

我相信解釋換行符作爲字符串,而不是一個字符創建了一個聲明不真實的情況,並反過來創建了一個不好的execlp()調用。