--- orig/filtersum
+++ mod/filtersum
@@ -121,13 +121,8 @@
                 if not args.quiet:
                     try:
                         print(line)
-                    # avoid traceback due to broken pipe on output stream
-                    except IOError as err:
-                        if err.errno == errno.EPIPE:
-                            sys.exit(os.EX_IOERR)
-                        raise
                     except BrokenPipeError:
-                        sys.exit(os.EX_IOERR)
+                        exit_brokenpipe()
                 else:
                     found = True
 
@@ -135,14 +130,20 @@
 
     if args.quiet and not found:
         sys.exit(1)
-    else:
-        sys.exit(os.EX_OK)
 
 class UsageAction(argparse.Action):
     def __call__(self, parser, namespace, values, option_string=None):
         parser.print_usage()
         parser.exit(os.EX_USAGE)
 
+def exit_brokenpipe():
+    # redirect output stream to /dev/null avoid additinal BrokenPipeError
+    # in TextIOWrapper during cleanup
+    devnull = os.open(os.devnull, os.O_WRONLY)
+    os.dup2(devnull, sys.stdout.fileno())
+
+    sys.exit(os.EX_IOERR)
+
 def error(msg):
     sys.stderr.write("{prog}: {message}\n".format(
         prog=os.path.basename(sys.argv[0]),
@@ -154,3 +155,10 @@
         main()
     except KeyboardInterrupt:
         sys.exit(128 + signal.SIGINT)
+    finally:
+        try:
+            sys.stdout.flush()
+        except BrokenPipeError:
+            exit_brokenpipe()
+
+    sys.exit(os.EX_OK)
