2017-01-10 47 views
0

我想運行以下命令「ls | date」,但每當我隔離ls和日期時,它們都不會使用execvp執行。C中的Shell命令(使用Execvp時出錯)

問題:

Isolated:ls 
ls: impossible to acess 'ld-linux-x86-64.so.2': Unknown directory or file 
ls: impossible to acess 'ld-linux-x86-64.so.2': Unknown directory or file 
Isolated: date 
ls: impossible to acess 'date': Unknown directory or file 

在代碼中,我想要查詢的 「;」但是當我檢查「」& &「|」它隔離我想要的參數......但它們不運行。

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

int main() { 

char command_line[256]="ls | date"; 
char *ptr_current_command; 
char *saveptr1; 
char *saveptr2; 
char *saveptr3; 
char *ptr_current_parameter; 
char *ptr_current_parameter2; 

char *str[256]; 
int i=0; 
int wait_child; 
pid_t pid; 



    //Uses Strtok to recognize token ";"  
    ptr_current_command=strtok_r(command_line, ";", &saveptr1); 
while (ptr_current_command != NULL) { 
    //printf("current_command: %s\n", ptr_current_command); 

    //Uses Strtok to recognize token " " 
    ptr_current_parameter=strtok_r(ptr_current_command, " ", &saveptr2); 
    while(ptr_current_parameter != NULL){ 
     //printf("\tcurrent_parameter: %s\n", ptr_current_parameter); 

     //Uses Strtok to recognize token "|" 
     ptr_current_parameter2=strtok_r(ptr_current_parameter, "|", &saveptr3); 
     while(ptr_current_parameter2 != NULL){ 
      printf("\t\tIsolei: %s\n", ptr_current_parameter2); 


      str[i]=ptr_current_parameter2; 
      i++;   
      //Closes token by token until final NULL of "|" 
      ptr_current_parameter2=strtok_r(NULL, "|", &saveptr3); 
     } 


     pid=fork(); 
    if (pid < 0) { perror("fork"); exit(errno); } 
    if (pid == 0){ 
     execvp(str[0], str); 
     perror("execvp"); exit(errno); 
     } 
    if (wait_child) 
     waitpid(pid, NULL, 0);  

     //Fecha Delimitador Espaço 
     ptr_current_parameter=strtok_r(NULL, " ", &saveptr2); 
     } 


    //Closes token by token until final NULL of ";"   
    ptr_current_command=strtok_r(NULL, ";", &saveptr1); 
    } 

return 0; 
} 
+0

嘗試'/斌/ ls' ... – Stargateur

+0

哪裏這個 「'不可能acess'」 從何而來? – alk

+0

我不知道... – Bitsized

回答

1

這裏有兩個問題。

首先,您不正確地建立str。它必須在最後一個參數後包含一個NULL指針值,否則execvp將不知道哪個選項是最後一個。

由於str未初始化,超出您在內部設置的元素的內容未定義。嘗試讀取這些元素(如execvp一樣)會調用undefined behavior

內循環之後,您需要將當前索引設置爲NULL

第二個問題是您在進入內循環時不會將i重置爲0。因此,即使第一個命令有效,第二個命令也不會,因爲它會繼續寫入第一個命令的參數。

你的內循環應該是這樣修復後:

i = 0; // reset i for each command 
    while(ptr_current_parameter2 != NULL){ 
     printf("\t\tIsolei: %s\n", ptr_current_parameter2); 


     str[i]=ptr_current_parameter2; 
     i++;   
     //Closes token by token until final NULL of "|" 
     ptr_current_parameter2=strtok_r(NULL, "|", &saveptr3); 
    } 
    str[i] = NULL; // terminate the list 
+0

好吧,我現在明白我的問題在哪裏,但我想出了一個不同的問題...問題:無法訪問ld-linux-x86-64.so.2 – Bitsized

+0

@Anomime您是否能夠成功運行'ls'命令行本身? – dbush

+0

沒有當我編譯和運行它給我的錯誤ld-linux-x86-64.so.2無法訪問。我編譯是這樣的:gcc .c -o Bitsized