0

I have a method execfile which takes the path of an executable file and then executes it, I'm now trying to add the option for the user to enter arguments to the command being executed. I currently have it implemented like so:

int execfile(char *file) {
    printf("Enter any arguments to %s: ", file);

    char *arg = (char *) calloc(ARG_MAX, sizeof(char));
    scanf("%s", arg);

    execl(file, file, arg, NULL);
    return -1;
}

This does function crudely in that I can execute /usr/bin/ps and enter el or -el at the argument prompt and the function will execute with both arguments as intended.

Ideally though it would be more elegant to be able to enter arguments as you traditionally would when executing a C program directly, so say enter -e -l at the prompt and have it correctly interpreted by the program (currently this wont work), or just immediately press enter to skip the prompt (currently have to enter at least some character).

I thought the best way to do this would be to declare an array char *argv[], set arg[0] = file then scan the rest of the input and place each separate argument in an array cell, then calling execv(file, argv).

I'm very new to C however and am unsure of how this can be implemented in the most efficient way, for example I was considering reading in the whole string first then using a loop to iterate through it character by character to recognise arguments to add to argv, but it seems a bit longwinded? Is there no way to read these arguments into the array directly from stdin?

Additionally I'm unsure what to set ARG_MAX to as I don't know what the limit on number of arguments is within C, and I don't know how to get it to recognise that the enter key has been pressed so to skip immediately.

transiti0nary
  • 493
  • 6
  • 25
  • See http://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c and similar questions for how to split a string into an array. – Barmar Nov 14 '16 at 19:12
  • Also, this `execl(... , NULL);` should be `execl(... , (char*) NULL);` – alk Nov 14 '16 at 20:16
  • "*Is there no way to read these arguments into the array*": This `char *argv[]` does not define an array, as it's of incomplete type, as the number of elements is not specified on compile time, not direct, nor indirect via an initialiser. – alk Nov 14 '16 at 20:20
  • BTW, there is no need to cast the result of `malloc()` & Friends in C, nor is it recommended in any way. – alk Nov 14 '16 at 20:28
  • Note that for a variable list of arguments, you will not be using `execl()` or `execlp()`; rather, you will be using one of `execv()`, `execvp()` or `execve()` — or perhaps `execvpe()` if it is available. – Jonathan Leffler Nov 14 '16 at 20:59

1 Answers1

0

Is there no way to read these arguments into the array directly from stdin?

In one go, without knowing how many whitespace delimited argument will be passed, and without additional parsing?

No.

alk
  • 69,737
  • 10
  • 105
  • 255