0

Пытаюсь написать калькулятор, в котором все вычисления производятся в дочернем процессе, после чего он возвращает результат родительскому. Программа отрабатывает корректно один раз, а дальше-выдает ошибку "Bad file descriptor"

В чем может быть причина? Все ломается как только добавляю цикл.

import os
class Calculator:

    operations = ['+', '-', '*', '/', '.']
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        return a / b

    def get_expression(self):
        user_input = input("Input the expression: op n1 n2 ")
        return bytes(user_input, encoding="UTF-8")

    def check_expression(self, expression):
        if len(expression) != 3 :
            return 0
        if (expression[0] not in self.operations):
            return 0
        else:
            return 1

    def check_quit(self, user_input):
        user_input = user_input.decode("utf-8").split()
        if user_input[0] == '.':
            return 1
        else:
            return 0

    def find_result(self, user_input):
        user_input = user_input.decode("utf-8").split()
        operand = user_input[0]
        a = int(user_input[1])
        b = int(user_input[2])
        if operand == '+':
            return str(my_cl.add(a, b)).encode("utf-8")
        elif (operand == '-'):
            return str(my_cl.subtract(a, b)).encode("utf-8")
        elif (operand == '*'):
            return str(my_cl.multiply(a, b)).encode("utf-8")
        elif (operand == '/'):
            return str(my_cl.divide(a, b)).encode("utf-8")
        else:
            print("ERROR")

my_cl = Calculator()

r2, w2 = os.pipe()
r1, w1 = os.pipe()

pid = os.fork()

while(1):
    if pid > 0:
        os.close(r2)
        os.close(w1)
        user_input = my_cl.get_expression()
        os.write(w2, user_input)
        print("Result:", os.read(r1, 100).decode("utf-8"))

    else:
        os.close(w2)
        os.close(r1)
        user_input = os.read(r2, 100)
        os.write(w1, my_cl.find_result(user_input))
4
  • 2
    Вытащите все close из цикла
    – avp
    18 сен в 17:01
  • Я пробовал разные варианты расстановки close-ов и все они выдают похожую ошибку: ``` lang-cpp pid = os.fork() </br> os.close(r2) </br> os.close(w1) </br> os.close(w2) os.close(r1) while(1): .... '``` **Input the expression: op n1 n2 Traceback (most recent call last): File "/home/slav/PycharmProjects/pp_hw1/main.py", line 72, in <module> user_input = os.read(r2, 100) OSError: [Errno 9] Bad file descriptor ** 19 сен в 5:27
  • А без цикла read/write отрабатывают нормально и вы получаете результат?
    – avp
    19 сен в 17:46
  • Да, без цикла все отрабатывает 25 сен в 8:35

1 ответ 1

0

Получилось! Правда выходит избыточный if и так и не понятно почему так получалось, но это работает.

import os

class Calculator:

    operations = ['+', '-', '*', '/', '.']

    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        return a / b

    def get_expression(self):
        user_input = input("Input the expression: op n1 n2 ")
        return bytes(user_input, encoding="UTF-8")

    def check_expression(self, expression):
        if len(expression) != 3:
            return 0
        if (expression[0] not in self.operations):
            return 0
        else:
            return 1

    def check_quit(self, user_input):
        user_input = user_input.decode("utf-8").split()
        if user_input[0] == '.':
            return 1
        else:
            return 0

    def find_result(self, user_input):
        user_input = user_input.decode("utf-8").split()
        operand = user_input[0]
        a = int(user_input[1])
        b = int(user_input[2])
        if operand == '+':
            return str(my_cl.add(a, b)).encode("utf-8")
        elif (operand == '-'):
            return str(my_cl.subtract(a, b)).encode("utf-8")
        elif (operand == '*'):
            return str(my_cl.multiply(a, b)).encode("utf-8")
        elif (operand == '/'):
            return str(my_cl.divide(a, b)).encode("utf-8")
        else:
            print("ERROR")


my_cl = Calculator()

r2, w2 = os.pipe()
r1, w1 = os.pipe()

pid = os.fork()

if pid > 0:
    os.close(r2)
    os.close(w1)
else:
    os.close(w2)
    os.close(r1)
while (1):
    if pid > 0:
        user_input = my_cl.get_expression()
        os.write(w2, user_input)
        print("Result:", os.read(r1, 100).decode("utf-8"))

    else:
        user_input = os.read(r2, 100)
        os.write(w1, my_cl.find_result(user_input))
1
  • Изучайте матчасть (OS, наверное лучше *nix) глубже. Файловый дескриптор (pipe создает именно их) можно закрывать только один раз. Поэтому в цикле и не работает
    – avp
    25 сен в 12:56

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.