简体   繁体   中英

Executing ls in a different directory in C using exec

Title is pretty self-explanatory on what I want to do.

My current try:

  chdir("/Path/I/want/");   //this is different that the path my program is located at
      char * ls_args[] = { "ls" , "ls -l", NULL};
      execv(ls_args[0], ls_args);
    }

I am not getting any errors or output, any help?

Execv function needs full path of the command which you have to execute. So, instead of giving "ls" , you should find out where the ls is located in your system by

$ which ls

it will probably be in /bin folder. So you have to give "/bin/ls" to exec. Also any argument to ls should be another member in array. So instead of using

char * ls_args[] = { "ls", "ls -l", NULL};

use

char * ls_args[] = { "/bin/ls", "-l", NULL};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM