linux下c/c++调用shell脚本
直接贴代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int shell_call(std::string &cmdstr);
int main(int argc, char **argv)
{
string shell_dir = "./test.sh";
string shell_command = "cat test.cpp";
shell_call(shell_command);
return 0;
}
int shell_call(std::string &cmdstr) {
//enum { maxline=100 };
int maxline = 100; //读取的shell命令最大长度
char line[maxline]; //存储读取到的shell命令
FILE *fpin; //文件控制指针
//popen以只读方式创建管道
if((fpin = popen(cmdstr.c_str(), "r")) == NULL)
{
printf("popen error\n");
exit(-1);
}
while(true)
{
//向控制台输出字符信息,stdout为标准输出流
fputs("prompt> ", stdout);
// fflush(stdout); //显示输出缓冲区信息并清空输出缓冲区
//从文件流中读取信息到line中
if(fgets(line, sizeof(line), fpin) == NULL) /*read from pipe*/
break;
//将line中信息送入输出缓冲区显示
if(fputs(line, stdout) == EOF)
{
printf("fputs error\n");
exit(-1);
}
}
//关闭shell执行管道
int ret;
if((ret = pclose(fpin)) == -1) {
printf("pclose error\n");
exit(-1);
}
return ret;
}
该程序可直接调用shell脚本文件或者shell命令,直接将shell文件路径或者shell命令传入shell_call函数即可。
FILE为c语言控制文件管理的结构体
FILE结构体解释
popen函数会创建通道执行shell命令,其返回值为FILE指针,其接收参数可以为shell文件路径也可以是shell命令。
其函数声明为:
FILE *popen(const char *command, const char *type);
该函数创建的通道必须由pclose函数来关闭:
int pclose ( FILE * stream );
while循环中fputs("prompt> ", stdout);
该行是将参数1的字符串放入标准输出流中,stdout就是标准输出流,执行脚本显示信息时会首先显示该字符串。
fflush(stdout)就是清空输出缓冲区并将其显示到终端,由于前面那句fputs已经显示输出流了,所以该句可以不加。
fflush函数详解
fgets函数会从FILE流中读取信息,每次读取一行,并存储在line中,遇到文件末尾时返回NULL,sizeof(line) - 1为最大读取的字符数。
fgets函数
fputs函数将line中的信息送入输出缓冲区显示,出错则返回EOF。
fgets和fputs
popen函数执行脚本显示的信息送入到了FILE流中,而fgets和fputs函数读取和显示每次只有一行,所以需要在外层套一个while循环。
最后fclose关闭通道,成功返回0,失败返回-1。
关于c/c++调用shell命令的其它方法也可以参考:
shell命令调用