我的工作流程是"编译cpp" - > "执行它" - > "记录消息"。
但是当cpp文件存在" scanf'或者&#c;' cin'命令"
因为这是一个自动编译&运行程序,还有一个需要加载的其他输入。 (来自函数调用的字符串不是由我自己输入终端)
如何运行executeCommand
(在compiler.cpp下面的代码中),使用字符串input
(也在下面)输入此程序。如果执行的程序存在任何scanf
,cin
或其他命令。
这是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;
}
#include <stdlib.h>
#include <stdio.h>
int main () {
char str[256];
scanf("%s", str);
printf("%s\n", str);
return 0;
}
答案 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问题,尤其是在将计算命令传递给popen
或system
event loop周围可能需要一些poll(2)。然后明确使用fork
,execve
,pipe
和其他syscalls(2),请阅读Advanced Linux Programming
答案 1 :(得分:0)
您只需要一个管道,系统(&#34;回显YOUR_STRING | ./main.out&#34;)