2011-08-31 39 views
0

如果您在代码中的任何位置调用store_commands()方法,则由于某种原因,命令的执行失败。为什么当我调用方法时,execvp失败?

如我的主要方法

int main (int argc, char * argv[]) { 

     char *command; 

     store_commands(); // problem 


     while ((command = readline(" $ "))!= NULL) { // scan stdin 

       rl_bind_key('\t',rl_complete); 


       splitCommands(&mainVars, command, argv); 
     } 


     return 0; 
} 

我店里命令方法

void store_commands() { 
     char *newEnv; 
     DIR * dir; 
     char *new ;   
     struct dirent * entry; 
     char *env = getenv("PATH"); 
     do { 
       newEnv = strsep(&env, ":"); 

       if(newEnv != NULL) 
         if(strlen(newEnv) > 0) { 

           dir = opendir(newEnv); 
           if(dir == NULL) break; 
           if(flag == 1) { 
             flag = 0; 
             while((entry = readdir(dir)) != NULL) { 
               new = malloc(strlen(entry->d_name) + 1) ; 
               new = strcpy(new, entry->d_name); 

               commands[++count] = new; // add possible commands into an array 
               //printf("---%i %s\n", count ,commands[count]); 
             } 
           } 
           closedir(dir); // close directory 
         } 
     } while(newEnv); 

} 

测试用例

without store_commands() 

**ls** 
comm[0]: 'ls' and comm[1]: '(null)' // command received here 

Makefile   
main.c      
target 
libedit.2.dylib 

with store_commands() 

**ls** 
comm[0]: 'ls' and comm[1]: '(null)' // command received here again but.... 
Execution of the command is failed 
: No such file or directory 
+1

你在哪里调用'execvp'? –

回答

1

您与strsep破坏环境。拨打env致电strdup

小例子:

#include <stdlib.h> 

int main() 
{ 
    char* z = getenv("PATH"); // <---- z points to the actual env, not a copy 
    *z = 0;      // <---- corrupt the environment 
    system("ls");    // <---- fail 
} 
+0

我该怎么称呼它?你可以提供一个例子吗?其固定的 – kanoz

+0

非常感谢..津巴布韦的大问候 – kanoz

+0

http://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c – Naytzyrhc

相关问题