linux下c/c++调用shell脚本

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

popen函数解释

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命令调用

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值