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.