C Program to Run External Command using System (Synchronous)

in #programming3 years ago

We can use the system function to run an external command. The method invokes the command synchronously and return the status code. Given the following C program, we first concatenate all command line paramters into a string/char buffer of size 256. And then we invoke the command string using system function from stdlib header. And return the status code as the main function.

This is just a wrapper of the command. You can echo $? to see the status code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
    if (argc == 0) {
        return 0;
    }
    char cmd[255];
    int s = 0;
    for (int i = 1; i < argc; ++ i) {
        strcpy(cmd + s, argv[i]);        
        s += strlen(argv[i]);
        cmd[s ++] = ' ';
    }
    cmd[s] = '\0';
    printf("Running `%s` ...\n", cmd);
    int ret = system(cmd);
    printf("Return Code: %d\n", ret);
    return ret;
}

Compiling the above C source e.g. run.c

$ gcc run.c -o run

And then run:

$ ./run echo HelloACM.com
Running `echo HelloACM.com ` ...
HelloACM.com
Return Code: 0
$ echo $?
0

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

Do not forget to mention that system 1) fork the shell (/bin/sh on nix systems) and 2) it can be a security risk and shouldn't be used lightheartly...

An interesting fact about sprintf is that it returns the number of bytes actually written. Hence the concatenation loop could look like:

      for (int i = 1; i < argc; ++i) {
                s += sprintf(buf + s, "%s ", argv[i]);
        }

An extra space will be written at the end of the buffer, and there's no check for buffer overflow (another security risk), as in your version.

Nice. thanks!

Coin Marketplace

STEEM 0.15
TRX 0.16
JST 0.028
BTC 67779.88
ETH 2396.01
USDT 1.00
SBD 2.32