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?
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().
popen() and fgets().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().system() just can't do that. You can do what alvits suggested.
systembutpopen.systemproduced on output, it is not intended for that. Why do you want to locate the it this way? Letexecvpdo the job for you...which, you can parse the envPATH. Usingstrtok(), get each path and check for existence of command in each of the path extracted fromPATH. Or useexecvpe(),execle()and pass the environment, which includesPATH.