skydoor
skydoor

Reputation: 25868

How to call execute command line in C++

For example, I have a script ./helloworld.sh

I would like to call it in C++, how do I do that? Which library can be used?

Upvotes: 4

Views: 1038

Answers (6)

Vojtech Vitek - golang.cz
Vojtech Vitek - golang.cz

Reputation: 27734

There are at least two possible ways. (I suppose you are asking about Unix-like systems when using shell scripts).

The first one is very simple, but is blocking (it returns after the command has been completed):

/* Example in pure C++ */
#include <cstdlib>
int ret = std::system("/home/<user>/helloworld.sh");

/* Example in C/C++ */
#include <stdlib.h>
int ret = system("/home/<user>/helloworld.sh");

The second way is not that easy, but could be non-blocking (script can be run as parallel process):

/* Example in C/C++ */
#include <unistd.h>
pid_t fork(void);
int execv(const char *path, char *const argv[]);

/* You have to fork process first. Search for it, if you don't know how to do it.
 * In child process you have to execute shell (eg. /bin/sh) with one of these
 * exec* functions and you have to pass path-to-your-script as the argument.
 * If you want to get script output (stdout) on-the-fly, you can do that with
 * pipes. Just create the reading pipe in parent process before forking
 * the process and redirect stdout to the writing pipe in the child process.
 * Then you can just use read() function to read the output whenever you want.
 */

Upvotes: 1

Loki Astari
Loki Astari

Reputation: 264401

If you just want to run it (and nothing else)

system("./helloworld.sh");

If you need to get the stdin/stdout then you need to use popen()

FILE*  f = popen("./helloworld.sh","r");

Upvotes: 5

valexa
valexa

Reputation: 4503

if you also want to get the output of the script do

char fbuf[256];
char ret[2555]; 
FILE *fh;
if ((fh = popen("./helloworld.sh", "r")) == NULL) {
    return 0;
}else{
    while ( fgets(fbuf, sizeof(fbuf), fh) ) {   
     strcat(ret, fbuf);            
     }          
}
pclose(fh);

Upvotes: 0

jdehaan
jdehaan

Reputation: 19928

In C there are also the execxxx functions from unistd.h. They have a big advantage over the simple system as you can specify environment variables for your process to run in among other levels of control for the arguments management.

Upvotes: 1

KLee1
KLee1

Reputation: 6178

try system().

Upvotes: 3

bits
bits

Reputation: 8340

try

system("./helloworld.sh");

Upvotes: 10

Related Questions