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

时间:2016-03-11 09:13:25

标签: c++ c popen

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

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

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

但是当cpp文件存在" scanf'或者&#c;' cin'命令"

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

我的问题

如何运行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;
}

2 个答案:

答案 0 :(得分:3)

您可能需要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)。然后明确使用forkexecvepipe和其他syscalls(2),请阅读Advanced Linux Programming

答案 1 :(得分:0)

您只需要一个管道,系统(&#34;回显YOUR_STRING | ./main.out&#34;)