-2

How can I execute the following command using execvp, if it's possible:

"ls | tee ~/outputfile.txt"

I've tried to run the following code but got this message: execvp() not expected: No such file or directory I'm not sure for the cause of this issue, I can't execute this command because this is concatenation command ?

#include <unistd.h> // execvp()
#include <stdio.h>  // perror()
#include <stdlib.h> // EXIT_SUCCESS, EXIT_FAILURE


int main(void) {
char *const cmd[] = {"ls | tee ~/outputfile.txt", NULL};
execvp(cmd[0], cmd);
perror("Return from execvp() not expected");

exit(EXIT_FAILURE);
}

In the bottom line, want to write the output of the command 'ls' to a file in my code.

Thank you in advance!

Ido Segal
  • 430
  • 2
  • 7
  • 20
  • 3
    `*exec*()` is not a shell. You could `*exec*("bash -c [whatever]")`. – EOF Nov 28 '18 at 14:45
  • 2
    You could run your string with `system()`. To use `execvp()`, you’ll need to parse it and create pipes and deal with word expansion on the file name and do the I/O redirection. – Jonathan Leffler Nov 28 '18 at 14:45

1 Answers1

1

You can't use execvp (or any exec* function family) like that. First of all, the first argument must be the path to the executable file. I doubt you have an 'ls | tee ~/outputfile.txt' executable somewhere on your computer. You have 'ls' or 'tee' probably, but not 'ls | tee ~/outputfile.txt'.

Secondly : exec* function family can't do nativly piping (the '|' part) : you have to do it yourself.

An example is the following :

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *const cmd[] = {"ls", "/home", NULL};
    execvp(cmd[0], cmd);
    perror("Return from execvp() not expected");

    exit(EXIT_FAILURE);
}

That will do a ls in "/home". It's up to you to pipe it in another execve : this can greatly help you.

If you just want to execute your command line wthout any regard for security, you can use "system"

Tom's
  • 2,448
  • 10
  • 22