How to call a function with a variable number of parameters?

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

+3
source share
4 answers

If you do not know how many arguments you will need at the time of writing the 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);
+9
source

This only answers 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;
}
+1
source

execlp() , :

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);
0

Execlp . ? , :

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

, , , , ,

0
source

Source: https://habr.com/ru/post/1729353/


All Articles