Husky
Husky

Reputation: 542

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

I want to build a compile system in an online judge system.

Environment: Ubuntu 12.04 LTS, g++ version 4.9


My workflow is "Compile cpp" -> "Execute it" -> "Record message".

But I got some problems when "the cpp file exist 'scanf' or 'cin' commands".

Because this is a auto-compile & run program, there is an other input need to load. (Is a string from function call not enter in terminal by myself)


My problem

How can I run the executeCommand (below code in compiler.cpp), using the string input (below too) to enter for this program. If the executed program exist any scanf, cin or other commands.


compiler.cpp

This is system command version, can replace to popen command too.

#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;
}

Upvotes: 2

Views: 360

Answers (2)

You probably need popen(3) (and you flagged your question as such).

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); }; 

Be aware of code injection issues, in particular when passing a computed command to popen or system

You might need some event loop around poll(2). Then use fork, execve, pipe and other syscalls(2) explicitly, so read Advanced Linux Programming

Upvotes: 3

where23
where23

Reputation: 513

All you need is a pipe, system( "echo YOUR_STRING | ./main.out " )

Upvotes: 0

Related Questions