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:
#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
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Important Update of Delegation Service!
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- 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
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:
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!