C Program to Run External Command using System (Synchronous)


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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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;
}
#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

1
$ gcc run.c -o run
$ gcc run.c -o run

And then run:

1
2
3
4
5
6
$ ./run echo HelloACM.com
Running `echo HelloACM.com ` ...
HelloACM.com
Return Code: 0
$ echo $?
0
$ ./run echo HelloACM.com
Running `echo HelloACM.com ` ...
HelloACM.com
Return Code: 0
$ echo $?
0

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
252 words
Last Post: Teaching Kids Programming - Sort List by Reversing Once
Next Post: Teaching Kids Programming - Sort List by Hamming Weight

The Permanent URL is: C Program to Run External Command using System (Synchronous)

Leave a Reply