Just quickly scanning your code, you have some "close"(s) that are not being handled.

try: $rc=close(1)
_________________________
(... better days ahead)