2

I need to have an input that looks like

./a.out <exe> <arg1> ... <argn> <others_stuff>

where <exe> <arg1> ... <argn> is the input that I must execute as a separate process (the objective is to save the exe's output into a txt).

Saving output into a txt file isn't a problem, I just have to redirect stdout (using dup2, freopen, or something similar).

The problem is to execute just a portion of argv! Because exec's family functions (they are so many!) let to give as input whole argv, or specifying each arg. I'm writing over here because I can't solve the problem, so I hope you're going to help me (I googled everywhere with no success).

EDIT: I forgot to say that i cannot use system for execute the command!

2

2 Answers 2

4

If you want to use a contiguous portion of argv, you have two options, you can (as you have tried) create a new arg array, properly filling it as so:

  char *params[argc-2];
  memcpy(params, argv+1, sizeof params);
  params[argc-3] = NULL;

  execvp(*params, params);

You could just smash argv

  argv[argc-3] = NULL;
  execvp(argv[1], argv+1);

Or if you don't have too many args, you can use execlp:

  execlp(argv[0], argv[0], argv[3], argv[2], argv[4], NULL);
Sign up to request clarification or add additional context in comments.

6 Comments

I used the second one, because after that i don't need argv anymore. It worked properly with "ls" command, but with "mkdir" doesn't. It says "missing argument for mkdir" or something like that (english isn't my mother tongue)
Smashing argv looks simplest. "smashing" sounds bad, but doing it after fork and before execvp means it can't break any other uses of argv.
@Black27 use a simple "printargs" program to make sure you're using the args you want.
Thank you for answering, I solved the problem! Simply I did a while iteration from 1 to argc-2 instead argc-1...What a stupid mistake!
@dave In this approach is there any requirement that params reside in the heap, or could params be a local variable?
|
1

Since exec accepts an argv argument as a char* array terminated by a NULL pointer, you can just use the existing argv and set the member after the last one you want to pass to NULL.

This does destroy argv - if that's a problem, you can copy it first (you'll have to allocate some memory for the new copy...)

Comments

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.