I am trying to write code that takes user input and passes this input to the execlp function.
Right now I am working with the scenario that the user will type 'ls -pla' as a way to familiarize myself with the process before adding additional features. To shorten my code, I omitted the loops to initialize the PATH variable. To simplify the below code, I just initialized the PATH variable with "ls" for this example. The code behaves the same way either way.
I use the fgets() function to get the user input and write it to an array called buf. I then change the last character of the array from a newline to a null terminator.
I then use an array of pointers to strings called args. I initialize the args[0] to the PATH array and args[1] to the buf array.
When I pass args[0] and args[1] to execlp, the function appears to read args[0] just fine. But it is not reading args[1].
I left comments in the below code to show my thought processes. Basically I want to get the remaining user input read by the function, but my approach isn't working.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main ()
{
char buf[500];
char* args[250];
char PATH[2] = "ls";
memset(buf, '\0', sizeof(buf));
memset(args, '\0', sizeof(args));
printf("Type command: ");
fgets(buf, 500, stdin);
buf[(strlen(buf)-1)] = '\0'; //Did this to change newline character to null terminator.
printf("You typed: %s\n", buf);
args[0] = PATH;
args[1] = buf;
printf("PATH %s\n", PATH); //prints: ls
printf("buf: %s\n", buf); //prints: ls -pla
printf("args[0]: %s\n", args[0]); //prints ls
printf("args[1]: %s\n", args[1]); //prints ls -pla
printf("*args: %s\n", *args); //prints ls
//The below function registers the first argument and the
//terminal behaves as if I had typed 'ls'.
//But the second argument is not going through.
//What am I doing wrong?
execlp(args[0], args[1], NULL);
}