I’m running some code for a program in python, and when I run c++ I need to handle standard input for my it, such as scanf and cin. I am running the compiled c++ program using subprocess.Popen. I expect it to time out and raise an exception when I don’t give any stdin, but my program ends straight away and prints Killed on the console.
Here’s part of my class, which I believe is sufficient
def run(
self, args: List[str] = [], stdin: str = "", timeout: int = 30
) -> Tuple[int, str, str]:
process = subprocess.Popen(
[os.path.join(self.temp_file_folder, "build", self.target_file_name)]
+ args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
stdout, stderr = process.communicate(input=stdin, timeout=timeout)
except subprocess.TimeoutExpired as e:
process.kill()
raise RunTimeoutError(f"Expired in {timeout}s")
return (process.returncode, stdout, stderr)
When I use 30s, the program exits directly after running process.communicate and prints Killed
on the console without any exception. But when I use 5s, it throws an exception as I expect.
I call my function without any stdin.
when timeout == 30 output like this:
when timeout == 5 output like this:
This is the c++ code I was running at the time
#include <iostream>
#include <cmath>
#include <limits>
#include <iomanip>
int main()
{
int N;
double sum = 0;
double product = 1;
std::cout << "Please enter an integer N between 1 and 50: ";
std::cin >> N;
while (std::cin.fail() || N < 1 || N > 50)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Input error, please enter an integer N between 1 and 50: ";
std::cin >> N;
}
std::cout << N << ":" << std::endl;
for (int i = N - 1; i >= 0; i--)
{
int value = pow(2, i);
sum += value;
product *= value;
std::cout << value << (i > 0 ? ", " : "\n");
}
double geometric_mean = pow(product, 1.0 / N);
std::cout << std::fixed << std::setprecision(2);
std::cout << "sum: " << sum << std::endl;
std::cout << "avg: " << geometric_mean << std::endl;
return 0;
}
I’m not quite sure if it’s a problem with the c++ code, or with my own code
My environment is python 3.8.10
Ubuntu 20.04.6 LTS