Using a Single system() Call to Execute Multiple Commands in C

23,725

Solution 1

That depends on the shell being invoked to execute the commands, but in general most shells use ; to separate commands so something like this should work:

command1; command2; command3

[EDIT]

As @dicroce mentioned, you can use && instead of ; which will stop execution at the first command that returns a non-zero value. This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured. In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.

Solution 2

Use && between your commands. It has the advantage that it only continues executing commands as long as they return successful error codes. Example:

"cd /proc && cat cpuinfo"

Solution 3

One possibility comes immediately to mind. You could write all the commands to a script then run it with:

system ("cmd.exe /c \"x.cmd\"");

or, now that I've noticed you're running on Fedora:

system ("x.sh");
Share:
23,725
Chance
Author by

Chance

Current computer science graduate student and employed developer. Interests include information security, networking and adorable cats.

Updated on July 30, 2022

Comments

  • Chance
    Chance almost 2 years

    In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora). What is the syntax that will allow me to execute more than command through system()? (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.)

    I.e.:

    char command[] = "????? \r\n"; 
    system(command);
    
    • Jonathan Leffler
      Jonathan Leffler over 15 years
      Unless you are running on Windows, the carriage return (\r) is likely to cause trouble rather than give a benefit. You should be able to separate commands by newlines - or semi-colons as others have suggested.
    • Jonathan Leffler
      Jonathan Leffler over 15 years
      In terms of security, allowing remote programs to execute arbitrary commands is a fraught process, in general. It is least serious if the program locally runs with the privileges of the remote user; if it runs with any sort of elevated privileges, it is dire.