【问题标题】:How can I enter continuously by another C++ program in C system / popen command?如何在 C system / popen 命令中由另一个 C++ 程序连续输入?
【发布时间】:2016-03-11 09:13:25
【问题描述】:

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

环境: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;
}

【问题讨论】:

  • 有什么问题?
  • 对不起,我的基本英语,我现在加强我的描述。
  • 如果有人提交了一个删除所有文件的程序会怎样?
  • @AlanStokes,听起来很糟糕......我对这个问题没有任何想法,你能给我一些建议吗?
  • 我认为你应该阅读stackoverflow.com/questions/9405985/…

标签: c++ c popen


【解决方案1】:

您可能需要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

【讨论】:

    【解决方案2】:

    你只需要一个管道,系统(“echo YOU​​R_STRING | ./main.out”)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2012-04-28
      • 2013-10-09
      相关资源
      最近更新 更多