How do I execute a command and get the output of the command within C++ using POSIX?

前端 未结 11 1384
我在风中等你
我在风中等你 2020-11-21 05:39

I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system() function, but that will jus

11条回答
  •  遥遥无期
    2020-11-21 06:23

    Assuming POSIX, simple code to capture stdout:

    #include 
    #include 
    #include 
    #include 
    
    std::string qx(const std::vector& args) {
      int stdout_fds[2];
      pipe(stdout_fds);
    
      int stderr_fds[2];
      pipe(stderr_fds);
    
      const pid_t pid = fork();
      if (!pid) {
        close(stdout_fds[0]);
        dup2(stdout_fds[1], 1);
        close(stdout_fds[1]);
    
        close(stderr_fds[0]);
        dup2(stderr_fds[1], 2);
        close(stderr_fds[1]);
    
        std::vector vc(args.size() + 1, 0);
        for (size_t i = 0; i < args.size(); ++i) {
          vc[i] = const_cast(args[i].c_str());
        }
    
        execvp(vc[0], &vc[0]);
        exit(0);
      }
    
      close(stdout_fds[1]);
    
      std::string out;
      const int buf_size = 4096;
      char buffer[buf_size];
      do {
        const ssize_t r = read(stdout_fds[0], buffer, buf_size);
        if (r > 0) {
          out.append(buffer, r);
        }
      } while (errno == EAGAIN || errno == EINTR);
    
      close(stdout_fds[0]);
    
      close(stderr_fds[1]);
      close(stderr_fds[0]);
    
      int r, status;
      do {
        r = waitpid(pid, &status, 0);
      } while (r == -1 && errno == EINTR);
    
      return out;
    }
    

    Code contributions are welcome for more functionality:

    https://github.com/ericcurtin/execxx

提交回复
热议问题