为什么当我调用方法时,execvp会失败?

时间:2011-08-31 07:59:50

标签: c methods

如果在我的代码中的任何地方调用 store_commands()方法,则由于某种原因执行命令会失败。

比如我的主要方法

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 个答案:

答案 0 :(得分:1)

您正在使用strsep破坏环境。在strdup上致电env

一个最小的例子:

#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
}