【c/c++】如何调用【linux】shell命令行命令并获取命令行的输出内容

#include <stdio.h>
#include <string.h>
 
void executeCMD(const char *cmd, char *result)
{
    char buf_ps[1024];
    char ps[1024]={0};
    FILE *ptr;
    strcpy(ps, cmd);
    if((ptr=popen(ps, "r"))!=NULL)
    {
        while(fgets(buf_ps, 1024, ptr)!=NULL)
        {
//	       可以通过这行来获取shell命令行中的每一行的输出
//	   	   printf("%s", buf_ps);
           strcat(result, buf_ps);
           if(strlen(result)>1024)
               break;
        }
        pclose(ptr);
        ptr = NULL;
    }
    else
    {
        printf("popen %s error\n", ps);
    }
}
 
int main()
{
        char result[1024]={0};
        executeCMD("python /usr/xhh/pythonprojects/Demo1.py [1,2,3]", result);
//      这行是将每一行的输出拼接之后获取到了result字符串中了
        printf("%s", result);
        return 0;
}

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Linux中的管道(pipe)来获取命令行输出内容。在C++中,可以通过fork()函数创建一个子进程,并在子进程中执行要获取输出命令。然后,将子进程的标准输出重定向到管道的写端,父进程从管道的读端读取命令行输出。 下面是一个简单的示例代码: ```cpp #include <iostream> #include <unistd.h> #include <sys/wait.h> int main() { int pipefd[2]; pipe(pipefd); pid_t pid = fork(); if (pid == 0) { // 子进程中执行命令并将输出写入管道 close(pipefd[0]); // 关闭管道的读端 dup2(pipefd[1], STDOUT_FILENO); // 将标准输出重定向到管道的写端 // 执行命令 execlp("your_command", "your_command", nullptr); // 替换为你要执行的命令 // 执行失败则退出 std::cerr << "Failed to execute command" << std::endl; exit(1); } else { // 父进程从管道中读取命令行输出 close(pipefd[1]); // 关闭管道的写端 char buffer[4096]; ssize_t bytesRead; while ((bytesRead = read(pipefd[0], buffer, sizeof(buffer))) > 0) { // 处理读取到的数据,例如打印输出 std::cout.write(buffer, bytesRead); } // 等待子进程结束 int status; waitpid(pid, &status, 0); } return 0; } ``` 在上面的代码中,需要将"your_command"替换为你要执行的命令。执行该程序时,它将创建一个子进程来执行命令,并将命令行输出通过管道传递给父进程,父进程则读取并处理输出。你可以根据需要对读取到的数据进行进一步处理或存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值