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?

4
  • Don't use system but popen. Commented Dec 10, 2015 at 20:26
  • but I have to use system @Jean-BaptisteYunès Commented Dec 10, 2015 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... Commented Dec 10, 2015 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. Commented Dec 10, 2015 at 20:53

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

5 Comments

this is a programming assigment and I have to use which and execv()
Hmm. If you really want to do that, you can use popen() and fgets().
@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().
I can just use system() . not popen(). How can I do that? is it possible? @l3x
@esrtr Your requirements are unusual. system() just can't do that. You can do what alvits suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.