5

How do I call execlp() with a variable number of arguments for different processes?

1
  • 1
    Why not just use execvp if the number of arguments can vary at runtime? Commented Jan 21, 2010 at 8:07

4 Answers 4

10

If you don't know how many arguments you'll need at the time you are writing your code, you want to use execvp(), not execlp():

char **args = malloc((argcount + 1) * sizeof(char *));
args[0] = prog_name;
args[1] = arg1;
...
args[argcount] = NULL;

execvp(args[0], args);
Sign up to request clarification or add additional context in comments.

Comments

1

This answers only the title question

From Wikipedia Covers old and new styles

#include <stdio.h>
#include <stdarg.h>

void printargs(int arg1, ...) /* print all int type args, finishing with -1 */
{
  va_list ap;
  int i;

  va_start(ap, arg1); 
  for (i = arg1; i != -1; i = va_arg(ap, int))
    printf("%d ", i);
  va_end(ap);
  putchar('\n');
}

int main(void)
{
   printargs(5, 2, 14, 84, 97, 15, 24, 48, -1);
   printargs(84, 51, -1);
   printargs(-1);
   printargs(1, -1);
   return 0;
}

Comments

0

execlp() can be called with variable number or arguments, so just call:

int ret;
ret = execlp("ls", "ls", "-l", (char *)0);
ret = execlp("echo", "echo", "hello", "world", (char *)0);
ret = execlp("man", "man", "execlp", (char *)0);
ret = execlp("grep", "grep", "-l", "pattern", "file1", "file2", (char *)0);

Comments

0

Execlp already as a variable number of parameters. What do you want to do exactly ? You can probably a variadic macro :

#define myfind(...) execlp("find", "find", __VA_ARGS__)

This is a rather useless example, but without knowing more precisely what you wanted to do, that's all I could come up with

2 Comments

That's not the syntax for (standard) C99 variadic macros. Why continue to use it?
Sorry for this, what is the syntax then ?

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.