mosquitos
mosquitos

Reputation: 63

send mulitple args to system() in C

Assume, I have one line bash script that executes everything it has in arguments

#!/bin/bash
$1

So, the command ./one_line_script.sh "ls -lh" works fine. Also I have C code, that accepts arguments and send them to my bash script

  int main (int argc, char* argv[])
  {
     char command[1000];
     sprintf(command, "/path/to/one_line_script.sh %s", argv[1]);
     system(command);
   return 0;
  }

And here I've got a problem, because ./c_program "ls -lh" returns only ls output. It doesn't understand few arguments. How do I need to modify my C code, so it could accept few arguments?

Upvotes: 1

Views: 94

Answers (3)

dom0
dom0

Reputation: 7486

I would recommend to use fork and exec directly to avoid quoting issues altogether. Consider for example what happens if a ' is contained within an argument - when doing sprintf cmd-line butchering this leads to broken command lines.

int pid = fork();

if(pid == 0) {
    execl("/bin/sh", "sh", "-c", arg1, arg2, arg3, 0);
} else {
    int status=0;
    waitpid(pid, &status, 0);
}

Upvotes: 2

blue112
blue112

Reputation: 56442

You need to quote it in your sprintf too, or bash will only receive one argument :)

sprintf(command, "/path/to/one_line_script.sh '%s'", argv[1]);

I've added quotes (') around the %s.

You can also use $@ instead of $1 in your bash script, so it will take all arguments passed to it.

Upvotes: 0

SukkoPera
SukkoPera

Reputation: 621

Try:

int i;

command[0] = '\0';
for (i = 1; i < argc; i++)
  strcat (command, argv[i]);

system (command);

This should work, but please be aware that it has a lot of security hazards: first of all executing any possible command you get on the command line might allow users to do things they normally aren't allowed to (don't setuid your program!). Then the buffer might easily overflow and allow all kinds of stack smashing. So I'd say: only use this program as a learning tool, to learn manipulation of argc/argv and to begin thinking about security. Don't even compile it!

Upvotes: -1

Related Questions