例如,我有一个脚本./helloworld.sh
我想用C ++调用它,我该怎么做?可以使用哪个库?
答案 0 :(得分:10)
试
system("./helloworld.sh");
答案 1 :(得分:5)
如果你只想运行它(没有别的)
system("./helloworld.sh");
如果你需要获取stdin / stdout,那么你需要使用popen()
FILE* f = popen("./helloworld.sh","r");
答案 2 :(得分:3)
尝试system()。
答案 3 :(得分:1)
在C中,还有来自unistd.h
的{{3}}。它们比简单的system
有很大的优势,因为您可以指定环境变量,以便您的流程在参数管理的其他控制级别中运行。
答案 4 :(得分:1)
至少有两种可能的方法。 (我想你在使用shell脚本时会询问类Unix系统)。
第一个非常简单,但是阻塞(它在命令完成后返回):
/* 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");
第二种方式并不容易,但可以是非阻塞的(脚本可以作为并行进程运行):
/* 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.
*/
答案 5 :(得分:0)
如果你还想获得脚本的输出吗
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);