gpt4 book ai didi

c++ - 如何在 C system/popen 命令中连续输入另一个 C++ 程序?

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:53 30 4
gpt4 key购买 nike

我想在在线评判系统中搭建一个编译系统。

环境:Ubuntu 12.04 LTS,g++ 4.9 版


我的工作流程是“编译cpp”->“执行它”->“记录消息”。

但是当“cpp 文件存在‘scanf’或‘cin’命令时我遇到了一些问题”。

因为这是一个自动编译和运行的程序,所以需要加载其他输入。 (函数调用的字符串不是自己在终端输入的)


我的问题

如何运行 executeCommand(在 compiler.cpp 中的代码下方),使用字符串 input(也在下方)为该程序输入。如果执行的程序存在任何scanfcin或其他命令。


编译器.cpp

这是system命令版本,也可以替换为popen命令。

#include <string>
#include <cstdlib>
#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char ** argv) {
// Compiler one cpp file.
string compileCommand = "(g++ --std=c++11 ./main.cpp -o ./main.out) 2> main.err";
system(compileCommand.c_str());

// Execute this program.
string executeCommand = "(time timeout -k1s 0.01s ./main.out) > result.txt 2> time.txt";
system(executeCommand.c_str());

// I want the above main.out will scanf from this string.
string input = "Hello world, this is first line.\nThis is second line.";

return 0;
}

main.cpp

#include <stdlib.h>
#include <stdio.h>

int main () {
char str[256];
scanf("%s", str);
printf("%s\n", str);
return 0;
}

最佳答案

您可能需要 popen(3) (并且您这样标记了您的问题)。

FILE*pcmd = popen("time ./main.out", "w");
if (!pcmd) { perror("popen"); exit(EXIT_FAILURE); };
fprintf(pcmd, "Hello world, this is first line.\n");
fprintf(pcmd, "This is the second line.\n");
fflush(pcmd);
int bad = pclose(pcmd);
if (bad) {fprintf(stderr, "pclose failed %d\n", bad); };

注意 code injection问题,特别是在将计算命令传递给 popensystem

您可能需要一些 event loop周围poll(2) .然后使用forkexecvepipesyscalls(2)明确地,所以阅读Advanced Linux Programming

关于c++ - 如何在 C system/popen 命令中连续输入另一个 C++ 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35936149/

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