-2

I am trying to create a simple shell in C. I am having issues with using the execve() function. So I have my arguments declared as char *cmdargs[10]; which holds the arguments such as -a or -l. However, it does not work with my execute function and I assume that because this array does not have the command as the first argument, and I am not sure how to add the command to the first of the array. Assuming now the array is

cmdargs[] = {"-a", "-l", NULL};

I want to the array to be cmdargs[] = {"ls", "-a", "-l", NULL}; However, the command is declare as a pointer: char *cmd; so how I can add this pointer to the beginning of my array.

We Que
  • 5
  • 3
  • If the array is defined as `char *cmdargs[] = { "-a", "-l", NULL }`, then you simply don't have space to prepend the `"ls"`; you'll need to use a different array. A [MRE](https://stackoverflow.com/help/minimal-reproducible-example) would be helpful. – William Pursell May 02 '22 at 21:08
  • nvm, I did it this way: for (int r = size-1; r >= 0; r--) { cmdargs[r + 1] = cmdargs[r]; } cmdargs[0] = cmd; – We Que May 02 '22 at 21:11
  • if you're using an array with initialized values, why not use `execle()` instead? `execve()` is usually used when you're creating the array dynamically. – Barmar May 02 '22 at 21:21

1 Answers1

0

Here is how you can do if your array is *cmdargs[] = {"-a", "-l", NULL};

I used execv here for simplicity: execve ask for a null terminated env array as last argument

int main() {
    char *cmdargs[] = { "-a", "-l", NULL};

    int i = 0;
    while (cmdargs[i++])
        ;
//allocation of the size of a new array with one extra room
    char **tmp = malloc( sizeof(cmdargs) * ++i );
//add the path you need
    *tmp = "/bin/ls";
//null the end
    tmp[i] = NULL;
//copy what was on the previous
    i = -1;
    while (cmdargs[++i])
        tmp[i + 1] = cmdargs[i];
//use it..
    execv(tmp[0], tmp + 1);
}
l_-A-_l
  • 142
  • 8
  • soooo all I had to do is simply add one to my array. LMAAAAAAAAAAAAO I spent 5 hours trying to fix this. – We Que May 02 '22 at 21:22
  • Well yes If you can do like this otherwise copy it in a new one using malloc this is what I was editing... If it's ok like that ? I leave it as it is... – l_-A-_l May 02 '22 at 21:28
  • I just edited so it reply to your exact question :) – l_-A-_l May 02 '22 at 21:40