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 tha开发者_如何转开发t? Which library can be used?
try
system("./helloworld.sh");
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");
try system().
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.
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.
*/
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);
精彩评论