开发者

Why when I call method, execvp fails?

开发者 https://www.devze.com 2023-04-01 03:29 出处:网络
If you call store_commands() method anywhere in my code, execution of the command f开发者_JS百科ails for some reason.

If you call store_commands() method anywhere in my code, execution of the command f开发者_JS百科ails for some reason.

such as my main method

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

my store commands method

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);

}

test cases

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 


You are corrupting the environment with strsep. Call strdup on your env.

A minimal example:

#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

精彩评论

暂无评论...
验证码 换一张
取 消