1

I want to find path name with using which command like this:

system("which");

and then I use the output for a parameter for execv() function. How can I do that? Any suggestion?

P.P
  • 117,907
  • 20
  • 175
  • 238
esrtr
  • 99
  • 2
  • 12
  • Don't use `system` but `popen`. – Jean-Baptiste Yunès Dec 10 '15 at 20:26
  • but I have to use system @Jean-BaptisteYunès – esrtr Dec 10 '15 at 20:28
  • You can't easily get what the command run by `system` produced on output, it is not intended for that. Why do you want to locate the it this way? Let `execvp` do the job for you... – Jean-Baptiste Yunès Dec 10 '15 at 20:30
  • Instead of using `which`, you can parse the env `PATH`. Using `strtok()`, get each path and check for existence of command in each of the path extracted from `PATH`. Or use `execvpe()`, `execle()` and pass the environment, which includes `PATH`. – alvits Dec 10 '15 at 20:53

1 Answers1

3

You are trying to solve it in the wrong way. which uses the PATH variable to locate the given executable. Using which to get the path and then passing it to execv() is needless because there's another variant of exec* which does the same: execvp().


To read the output of a command, you can use popen():

#include <limits.h>
#include <stdio.h>


char str[LINE_MAX];
FILE *fp = popen("which ls", "r");

if (fp == NULL) {
   /* error */
}

if(fgets(str, sizeof str, fp) == NULL) {
   /* error */
}

/*remove the trailing newline, if any */
char *p = strchr(str, '\n');
if (p) *p = 0; 

If your binary is in some buffer then you can use snprintf() to form the first argument to popen().

P.P
  • 117,907
  • 20
  • 175
  • 238
  • this is a programming assigment and I have to use which and execv() – esrtr Dec 10 '15 at 20:31
  • Hmm. If you really want to do that, you can use `popen()` and `fgets()`. – P.P Dec 10 '15 at 20:36
  • @esrtr - if you insist on using `system()` and `which`, you have to create a pipe between the child process and the parent process. Set the `stdout` of the child process to the write end of the pipe. On parent process, read from the pipe to get the output of `which cmd`. Now with this output you can call `execvp()`. – alvits Dec 10 '15 at 21:03
  • I can just use system() . not popen(). How can I do that? is it possible? @l3x – esrtr Dec 10 '15 at 21:54
  • @esrtr Your requirements are unusual. `system()` just can't do that. You can do what alvits suggested. – P.P Dec 10 '15 at 22:27