简体   繁体   English

如何在C ++中调用execute命令行

[英]How to call execute command line in C++

For example, I have a script ./helloworld.sh 例如,我有一个脚本./helloworld.sh

I would like to call it in C++, how do I do that? 我想用C ++调用它,我该怎么做? Which library can be used? 可以使用哪个库?

尝试

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() 如果你需要获取stdin / stdout然后你需要使用popen()

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

试试system()

In C there are also the execxxx functions from unistd.h . 在C中还有来自unistd.hexecxxx函数 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. 它们比简单system具有很大的优势,因为您可以指定环境变量,以便您的流程在参数管理的其他控制级别之间运行。

There are at least two possible ways. 至少有两种可能的方式。 (I suppose you are asking about Unix-like systems when using shell scripts) . (我想你在使用shell脚本时会询问类Unix系统)

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM