0

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?

Sergio
  • 275
  • 1
  • 15
  • Why changing dir and not simply issuing `ls /Path/you/want/`? – Roberto Caboni Apr 06 '20 at 10:28
  • Two reasons: 1-I need to create a text file in this directory and I don't know how to do it directly (I realize this isn't the topic of the question but since you asked I am answering). 2-I tried `char * ls_args[] = { "ls /Path/I/want" , "-l", NULL)` then `execv(ls_args[0], ls_args)` and it also resulted in no output so this was my attempt at trying to fix it. – Sergio Apr 06 '20 at 10:34
  • 2
    1) Also the file can be created at a given path (for example specifying the full path in `fopen()` . 2) In order to access the ouptut of the executed command use `popen()` (on Linux) or `_popen()` (on Windows). I explain the use of the latter in this answer https://stackoverflow.com/a/61010544/11336762 (even if for a different command). – Roberto Caboni Apr 06 '20 at 10:38
  • 1
    I am well aware of this and thank you for mentioning but I was asked to do it using `exec` , not my choice but I really appreciate you mentioning this. – Sergio Apr 06 '20 at 10:40
  • 2
    In this case it's a bit more complicated, since `exec` functions do not provide a stream of the executed program's output that can be read from the calling program. This question explains how to do: you have to do a pipe (that's what popen() actually does..): https://stackoverflow.com/questions/7292642/grabbing-output-from-exec – Roberto Caboni Apr 06 '20 at 10:47
  • 1
    Alternatively you can just redirect the output to a file (something like `ls path > . out.txt`) and process it trough `fopen()`, `fgets()` and so on... – Roberto Caboni Apr 06 '20 at 10:49

1 Answers1

1

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