2

I'm unable to execute the command alone, with arguments is working. How can I make it work both ways.

char command[256];
char args[10][256];
char buffer[256] __attribute__((aligned(4096)));

Funcion is handling command and arguments and I'm sure they are correct, however I can't find a way to execute it.

pid = fork();
    if (pid == -1)
    {
      printf("Failed forming fork\n");
      return;
    }
    else if (pid == 0)
    {
      strcpy( cmd , "/usr/bin/");
      strcat( cmd, command);
      execl(cmd, command, args, NULL);

    }else{
      wait(NULL);
       }

And in general how can I stop fork bombs, how to check for them and avoid them?

  • You are not executing a *shell* command here, but just any binary. – Eugene Sh. Nov 16 '17 at 22:41
  • I'm sorry but I don't understand what you mean. Both command and arguments are parsed and they should call a coresponding binary in usr/bin with coresponding arguments. – Denz Zuckerpuppe Nov 16 '17 at 22:44
  • If you want to execute a shell command, you should do something similar to what `system` is doing, namely `execl("/bin/sh", "sh", "-c", command, (char *) 0);` – Eugene Sh. Nov 16 '17 at 22:46
  • As @EugeneSh. hinted, you are passing `args` incorrectly. If you want to pass in args as an array, use `execv`. – jxh Nov 16 '17 at 22:49
  • So I can't pass arguments that I saved in array to execl or any other exec variation? :/ – Denz Zuckerpuppe Nov 16 '17 at 22:50
  • @jxh I tried that variation, but I get: extern int execv (const char *__path, char *const __argv[]) , which means I need to change my array to char* ? – Denz Zuckerpuppe Nov 16 '17 at 22:55
  • @DzenzKajtz:Yes – jxh Nov 16 '17 at 23:01
  • Note that you need code after the `execl()` call that (probably) reports an error and definitely exits with a non-zero (failure) status. If there's other cleanup you need to do (relatively unlikely), then that too. You don't need to test the return value from `execl()`. If it returns, it failed. If it succeeds, it does not return (a different program (usually) is running instead of the child that was forked). – Jonathan Leffler Nov 17 '17 at 00:59

0 Answers0