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

How can I enter continuously by another C++ program in C system / popen command?

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

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


我的工作流程是 "Compile cpp" -> "Execute it" -> "Record message"。

但是我在 "the cpp file exist 'scanf' or 'cin' commands" 时遇到了一些问题。

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


我的问题

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


compiler.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 around poll(2). Then use fork, execve, pipe and other syscalls(2) explicitly, so read Advanced Linux Programming

你只需要一根管道,系统( "echo YOUR_STRING | ./main.out " )