gpt4 book ai didi

c++ - 无法使用重定向的标准输出调用 g++

转载 作者:行者123 更新时间:2023-11-30 02:33:55 24 4
gpt4 key购买 nike

我正在寻找调用 g++ 并获取输出。这是我的代码:

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <boost/optional.hpp>
#include <vector>
#include <string>

namespace Util
{
template<typename T>
using optional = boost::optional<T>;
}

namespace Wide
{
namespace Driver
{
struct ProcessResult
{
std::string std_out;
int exitcode;
};

ProcessResult StartAndWaitForProcess(std::string name, std::vector<std::string> args, Util::optional<unsigned> timeout);
}
}

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <fcntl.h>
Wide::Driver::ProcessResult Wide::Driver::StartAndWaitForProcess(std::string name, std::vector<std::string> args, Util::optional<unsigned> timeout) {
int filedes[2];
pipe(filedes);
pid_t pid = fork();
if (pid == 0) {
while ((dup2(filedes[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
auto fd = open("/dev/null", O_RDWR);
while ((dup2(fd, STDIN_FILENO) == -1) && (errno == EINTR)) {}
//freopen("/dev/null", "rw", stdin);
//freopen("/dev/null", "rw", stderr);
//close(filedes[1]);
close(filedes[0]);
std::vector<const char*> cargs;
cargs.push_back(name.c_str());
for (auto&& arg : args)
cargs.push_back(arg.c_str());
cargs.push_back(nullptr);
execv(name.c_str(), const_cast<char* const*>(&cargs[0]));
}
std::string std_out;
close(filedes[1]);
char buffer[4096];
while (1) {
ssize_t count = read(filedes[0], buffer, sizeof(buffer));
if (count == -1) {
if (errno == EINTR) {
continue;
} else {
perror("read");
exit(1);
}
} else if (count == 0) {
break;
} else {
std_out += std::string(buffer, buffer + count);
}
}
close(filedes[0]);
int status;
ProcessResult result;
result.std_out = std_out;
waitpid(pid, &status, 0);
if (!WIFEXITED(status))
result.exitcode = 1;
else {
result.exitcode = WEXITSTATUS(status);
if (result.exitcode != 0) {
std::cout << name << " failed with code " << result.exitcode << "\n";
}
}
return result;
}

int main()
{
auto r = Wide::Driver::StartAndWaitForProcess("g++", { "-std=c++14", "main.cpp" }, 150);
std::cout << r.std_out << "!!!!\n!!!!\n" << r.exitcode << "\n";
}

输出:

read: Bad file descriptor
g++ failed with code 1
!!!!
!!!!
1

只需调用 g++ main.cpp -std=c++14 && ./a.out

我使用过 strace,但它并没有真正提供任何更有趣的细节——进程运行,然后 fork/exec,然后出现上述错误。我可以用上面的代码调用其他进程,所以我不知道 g++ 有什么不同。我可以毫无问题地使用 popen 调用 GCC,所以我不知道这里有什么不同。

这里的error确实帮助不大。如何调用 g++ 并获取输出?

最佳答案

这里的问题是你调用了execv这需要可执行文件的完整路径作为其第一个参数。

你需要的是 execvp,它使用 PATH 环境变量的内容来查找可执行文件,因此只需要一个像 g++.

关于c++ - 无法使用重定向的标准输出调用 g++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com