首页主机资讯Ubuntu下C++如何调用外部程序

Ubuntu下C++如何调用外部程序

时间2025-12-01 20:22:04发布访客分类主机资讯浏览598
导读:在Ubuntu下,C++可以通过多种方式调用外部程序。以下是一些常用的方法: 使用system( 函数 system( 函数是最简单的方法,它允许你在C++程序中执行一个shell命令。例如: #include <cstdlib&...

在Ubuntu下,C++可以通过多种方式调用外部程序。以下是一些常用的方法:

  1. 使用system()函数

system()函数是最简单的方法,它允许你在C++程序中执行一个shell命令。例如:

#include <
    cstdlib>


int main() {
    
    int result = system("ls");
    
    return 0;

}
    

但是,system()函数有一些局限性,比如无法获取外部程序的输出,而且可能存在安全风险。

  1. 使用fork()exec()系列函数

fork()exec()系列函数提供了更强大的功能,可以让你创建一个新的进程并执行外部程序。例如:

#include <
    iostream>
    
#include <
    sys/types.h>
    
#include <
    sys/wait.h>
    
#include <
    unistd.h>


int main() {
    
    pid_t pid = fork();

    if (pid == 0) {
     // 子进程
        execl("/bin/ls", "ls", "-l", NULL);
    
        std::cerr <
    <
     "Error: exec failed\n";
    
        return 1;

    }
     else if (pid >
 0) {
     // 父进程
        int status;
    
        waitpid(pid, &
    status, 0);
    
        std::cout <
    <
     "Child process finished with status: " <
    <
     WEXITSTATUS(status) <
    <
     std::endl;

    }
 else {
    
        std::cerr <
    <
     "Error: fork failed\n";
    
        return 1;

    }
    
    return 0;

}
    
  1. 使用popen()函数

popen()函数允许你执行一个外部程序,并与其进行双向通信。例如:

#include <
    iostream>
    
#include <
    cstdio>


int main() {
    
    FILE* pipe = popen("ls -l", "r");

    if (!pipe) {
    
        std::cerr <
    <
     "Error: popen failed\n";
    
        return 1;

    }
    

    char buffer[128];

    while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
    
        std::cout <
    <
     buffer;

    }
    

    int status = pclose(pipe);

    if (status == -1) {
    
        std::cerr <
    <
     "Error: pclose failed\n";
    
        return 1;

    }
    

    return 0;

}
    
  1. 使用第三方库

还有一些第三方库可以帮助你在C++中调用外部程序,例如Boost.Process。这些库通常提供了更高级的功能和更好的错误处理。

例如,使用Boost.Process:

#include <
    boost/process.hpp>
    
#include <
    iostream>
    

namespace bp = boost::process;


int main() {
    
    std::string command = "ls -l";
    
    bp::ipstream pipe_stream;
    
    bp::child c(command, bp::std_out >
     pipe_stream);
    

    std::string line;
    
    while (pipe_stream &
    &
     std::getline(pipe_stream, line) &
    &
     !line.empty())
        std::cout <
    <
     line <
    <
     std::endl;
    

    c.wait();
    
    return 0;

}
    

在选择方法时,请根据你的需求和安全性考虑来选择合适的方法。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Ubuntu下C++如何调用外部程序
本文地址: https://pptw.com/jishu/760454.html
如何用copendir优化Linux文件系统操作 如何在Ubuntu上配置C++图形界面

游客 回复需填写必要信息