2016-03-10 110 views
0

當執行這一塊操作系統代碼我收到信息「退出值255」。我通過鍵盤接收命令,並且我得到了字符串正確的信息。當我收到錯誤信息時,程序不顯示(例如)鍵盤接收到的ls -lc WEXITSTATUS()退出255

printf("Command? "); 
    scanf(" %99[^\n]", str); 

    p = fork(); 
     if(p > 0){ //Dad wait for the child 
      wait(&status); 
      if(WIFEXITED(status)){ 
       printf("%d\n",WEXITSTATUS(status)); 
      } 
     }else{  //Child execute the execlp 
      execlp(str, str,NULL); 
      exit(-1); 
     } 

謝謝! Mark

+1

'exit -1;'是原因。順便說一句:你進入scanf()行到底是什麼?注意:'ls -l'不是一個程序。 'ls'是。 – wildplasser

+0

1)是的,現在幫助過程有一個狀態= 1這是很好的! 2)所以...我不能在execlp中使用ls -l? – Mark

回答

1

execlp()期望參數被分開;你的字符串輸入ls -l不是有效的現有的可執行程序:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/wait.h> 

char *args[] = { "ls", "-l" }; 
// int main (int argc, char **argv) 
int main (void) 
{ 
int p; 
int status; 

p = fork(); 
if(p > 0){ //Dad wait for the child 
    wait(&status); 
    if (WIFEXITED(status)){ 
     printf("%d\n", WEXITSTATUS(status)); 
     } 
    }else{  //Child execute the execlp 
     execlp(args[0], args[0], args[1] ,NULL); 
     exit (-1); 
    } 

exit (0); 
} 

還要注意的是exit(-1)(除了是無效的:你應該使用EXIT_FAILURE)產生0xaaaaaaFF的出口結果;只有較少的(8)位用於實際出口值;較高的位被用於退出的原因等等。 - >>查看WEXITSTATUS()的定義和<sys/wait.h>的朋友。

+0

工作非常感謝;)! – Mark

相關問題