We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
'Bad file descriptor' error logged in atexit call back 
**Issue:**  Following log lines are observed in stderr on daemonizing a process with `IPython.utils.io` as an import.
> Exception ignored in atexit callback: <built-in method close of _io.TextIOWrapper object at 0x7f19e8aa9b10>
> OSError: [Errno 9] Bad file descriptor


**Reproducer:**
```python
import daemon
import sys
import IPython.utils.io

file_descriptors_to_preserve = []
with daemon.DaemonContext(
    prevent_core=False,
    signal_map={},
    stderr=sys.stderr,
    stdout=sys.stdout,
    files_preserve=file_descriptors_to_preserve,
):
    pass 
```

**Root cause:**
This is due to the following lines in I**Python.utils.io module**
```python
# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
devnull = open(os.devnull, "w", encoding="utf-8")
atexit.register(devnull.close)
```
After the child process is launched, all the files opened by the parent process are closed(except for stderr, stdout). While closing all the files, devnull opened in the IPython.utils.io module is also closed. On process exit atexit module runs all the functions that were registered. Since devnull close is registered, atexit handler is trying to close the already closed file which is generating ' Bad file descriptor' log in stderr

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `IPython/utils/io.py`
Content:
```
1 # encoding: utf-8
2 """
3 IO related utilities.
4 """
5 
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
8 
9 
10 
11 import atexit
12 import os
13 import sys
14 import tempfile
15 from pathlib import Path
16 from warnings import warn
17 
18 from IPython.utils.decorators import undoc
19 from .capture import CapturedIO, capture_output
20 
21 # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
22 devnull = open(os.devnull, "w", encoding="utf-8")
23 atexit.register(devnull.close)
24 
25 
26 class Tee(object):
27     """A class to duplicate an output stream to stdout/err.
28 
29     This works in a manner very similar to the Unix 'tee' command.
30 
31     When the object is closed or deleted, it closes the original file given to
32     it for duplication.
33     """
34     # Inspired by:
35     # http://mail.python.org/pipermail/python-list/2007-May/442737.html
36 
37     def __init__(self, file_or_name, mode="w", channel='stdout'):
38         """Construct a new Tee object.
39 
40         Parameters
41         ----------
42         file_or_name : filename or open filehandle (writable)
43             File that will be duplicated
44         mode : optional, valid mode for open().
45             If a filename was give, open with this mode.
46         channel : str, one of ['stdout', 'stderr']
47         """
48         if channel not in ['stdout', 'stderr']:
49             raise ValueError('Invalid channel spec %s' % channel)
50 
51         if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):
52             self.file = file_or_name
53         else:
54             encoding = None if "b" in mode else "utf-8"
55             self.file = open(file_or_name, mode, encoding=encoding)
56         self.channel = channel
57         self.ostream = getattr(sys, channel)
58         setattr(sys, channel, self)
59         self._closed = False
60 
61     def close(self):
62         """Close the file and restore the channel."""
63         self.flush()
64         setattr(sys, self.channel, self.ostream)
65         self.file.close()
66         self._closed = True
67 
68     def write(self, data):
69         """Write data to both channels."""
70         self.file.write(data)
71         self.ostream.write(data)
72         self.ostream.flush()
73 
74     def flush(self):
75         """Flush both channels."""
76         self.file.flush()
77         self.ostream.flush()
78 
79     def __del__(self):
80         if not self._closed:
81             self.close()
82 
83 
84 def ask_yes_no(prompt, default=None, interrupt=None):
85     """Asks a question and returns a boolean (y/n) answer.
86 
87     If default is given (one of 'y','n'), it is used if the user input is
88     empty. If interrupt is given (one of 'y','n'), it is used if the user
89     presses Ctrl-C. Otherwise the question is repeated until an answer is
90     given.
91 
92     An EOF is treated as the default answer.  If there is no default, an
93     exception is raised to prevent infinite loops.
94 
95     Valid answers are: y/yes/n/no (match is not case sensitive)."""
96 
97     answers = {'y':True,'n':False,'yes':True,'no':False}
98     ans = None
99     while ans not in answers.keys():
100         try:
101             ans = input(prompt+' ').lower()
102             if not ans:  # response was an empty string
103                 ans = default
104         except KeyboardInterrupt:
105             if interrupt:
106                 ans = interrupt
107             print("\r")
108         except EOFError:
109             if default in answers.keys():
110                 ans = default
111                 print()
112             else:
113                 raise
114 
115     return answers[ans]
116 
117 
118 def temp_pyfile(src, ext='.py'):
119     """Make a temporary python file, return filename and filehandle.
120 
121     Parameters
122     ----------
123     src : string or list of strings (no need for ending newlines if list)
124         Source code to be written to the file.
125     ext : optional, string
126         Extension for the generated file.
127 
128     Returns
129     -------
130     (filename, open filehandle)
131         It is the caller's responsibility to close the open file and unlink it.
132     """
133     fname = tempfile.mkstemp(ext)[1]
134     with open(Path(fname), "w", encoding="utf-8") as f:
135         f.write(src)
136         f.flush()
137     return fname
138 
139 
140 @undoc
141 def raw_print(*args, **kw):
142     """DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print()."""
143     warn("IPython.utils.io.raw_print has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
144 
145     print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
146           file=sys.__stdout__)
147     sys.__stdout__.flush()
148 
149 @undoc
150 def raw_print_err(*args, **kw):
151     """DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print()."""
152     warn("IPython.utils.io.raw_print_err has been deprecated since IPython 7.0", DeprecationWarning, stacklevel=2)
153 
154     print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
155           file=sys.__stderr__)
156     sys.__stderr__.flush()
157
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/IPython/utils/io.py b/IPython/utils/io.py
--- a/IPython/utils/io.py
+++ b/IPython/utils/io.py
@@ -18,11 +18,6 @@
 from IPython.utils.decorators import undoc
 from .capture import CapturedIO, capture_output
 
-# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
-devnull = open(os.devnull, "w", encoding="utf-8")
-atexit.register(devnull.close)
-
-
 class Tee(object):
     """A class to duplicate an output stream to stdout/err.

{"golden_diff": "diff --git a/IPython/utils/io.py b/IPython/utils/io.py\n--- a/IPython/utils/io.py\n+++ b/IPython/utils/io.py\n@@ -18,11 +18,6 @@\n from IPython.utils.decorators import undoc\n from .capture import CapturedIO, capture_output\n \n-# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr\n-devnull = open(os.devnull, \"w\", encoding=\"utf-8\")\n-atexit.register(devnull.close)\n-\n-\n class Tee(object):\n     \"\"\"A class to duplicate an output stream to stdout/err.\n", "issue": "'Bad file descriptor' error logged in atexit call back \n**Issue:**  Following log lines are observed in stderr on daemonizing a process with `IPython.utils.io` as an import.\r\n> Exception ignored in atexit callback: <built-in method close of _io.TextIOWrapper object at 0x7f19e8aa9b10>\r\n> OSError: [Errno 9] Bad file descriptor\r\n\r\n\r\n**Reproducer:**\r\n```python\r\nimport daemon\r\nimport sys\r\nimport IPython.utils.io\r\n\r\nfile_descriptors_to_preserve = []\r\nwith daemon.DaemonContext(\r\n    prevent_core=False,\r\n    signal_map={},\r\n    stderr=sys.stderr,\r\n    stdout=sys.stdout,\r\n    files_preserve=file_descriptors_to_preserve,\r\n):\r\n    pass \r\n```\r\n\r\n**Root cause:**\r\nThis is due to the following lines in I**Python.utils.io module**\r\n```python\r\n# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr\r\ndevnull = open(os.devnull, \"w\", encoding=\"utf-8\")\r\natexit.register(devnull.close)\r\n```\r\nAfter the child process is launched, all the files opened by the parent process are closed(except for stderr, stdout). While closing all the files, devnull opened in the IPython.utils.io module is also closed. On process exit atexit module runs all the functions that were registered. Since devnull close is registered, atexit handler is trying to close the already closed file which is generating ' Bad file descriptor' log in stderr\n", "before_files": [{"content": "# encoding: utf-8\n\"\"\"\nIO related utilities.\n\"\"\"\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n\n\nimport atexit\nimport os\nimport sys\nimport tempfile\nfrom pathlib import Path\nfrom warnings import warn\n\nfrom IPython.utils.decorators import undoc\nfrom .capture import CapturedIO, capture_output\n\n# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr\ndevnull = open(os.devnull, \"w\", encoding=\"utf-8\")\natexit.register(devnull.close)\n\n\nclass Tee(object):\n    \"\"\"A class to duplicate an output stream to stdout/err.\n\n    This works in a manner very similar to the Unix 'tee' command.\n\n    When the object is closed or deleted, it closes the original file given to\n    it for duplication.\n    \"\"\"\n    # Inspired by:\n    # http://mail.python.org/pipermail/python-list/2007-May/442737.html\n\n    def __init__(self, file_or_name, mode=\"w\", channel='stdout'):\n        \"\"\"Construct a new Tee object.\n\n        Parameters\n        ----------\n        file_or_name : filename or open filehandle (writable)\n            File that will be duplicated\n        mode : optional, valid mode for open().\n            If a filename was give, open with this mode.\n        channel : str, one of ['stdout', 'stderr']\n        \"\"\"\n        if channel not in ['stdout', 'stderr']:\n            raise ValueError('Invalid channel spec %s' % channel)\n\n        if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):\n            self.file = file_or_name\n        else:\n            encoding = None if \"b\" in mode else \"utf-8\"\n            self.file = open(file_or_name, mode, encoding=encoding)\n        self.channel = channel\n        self.ostream = getattr(sys, channel)\n        setattr(sys, channel, self)\n        self._closed = False\n\n    def close(self):\n        \"\"\"Close the file and restore the channel.\"\"\"\n        self.flush()\n        setattr(sys, self.channel, self.ostream)\n        self.file.close()\n        self._closed = True\n\n    def write(self, data):\n        \"\"\"Write data to both channels.\"\"\"\n        self.file.write(data)\n        self.ostream.write(data)\n        self.ostream.flush()\n\n    def flush(self):\n        \"\"\"Flush both channels.\"\"\"\n        self.file.flush()\n        self.ostream.flush()\n\n    def __del__(self):\n        if not self._closed:\n            self.close()\n\n\ndef ask_yes_no(prompt, default=None, interrupt=None):\n    \"\"\"Asks a question and returns a boolean (y/n) answer.\n\n    If default is given (one of 'y','n'), it is used if the user input is\n    empty. If interrupt is given (one of 'y','n'), it is used if the user\n    presses Ctrl-C. Otherwise the question is repeated until an answer is\n    given.\n\n    An EOF is treated as the default answer.  If there is no default, an\n    exception is raised to prevent infinite loops.\n\n    Valid answers are: y/yes/n/no (match is not case sensitive).\"\"\"\n\n    answers = {'y':True,'n':False,'yes':True,'no':False}\n    ans = None\n    while ans not in answers.keys():\n        try:\n            ans = input(prompt+' ').lower()\n            if not ans:  # response was an empty string\n                ans = default\n        except KeyboardInterrupt:\n            if interrupt:\n                ans = interrupt\n            print(\"\\r\")\n        except EOFError:\n            if default in answers.keys():\n                ans = default\n                print()\n            else:\n                raise\n\n    return answers[ans]\n\n\ndef temp_pyfile(src, ext='.py'):\n    \"\"\"Make a temporary python file, return filename and filehandle.\n\n    Parameters\n    ----------\n    src : string or list of strings (no need for ending newlines if list)\n        Source code to be written to the file.\n    ext : optional, string\n        Extension for the generated file.\n\n    Returns\n    -------\n    (filename, open filehandle)\n        It is the caller's responsibility to close the open file and unlink it.\n    \"\"\"\n    fname = tempfile.mkstemp(ext)[1]\n    with open(Path(fname), \"w\", encoding=\"utf-8\") as f:\n        f.write(src)\n        f.flush()\n    return fname\n\n\n@undoc\ndef raw_print(*args, **kw):\n    \"\"\"DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n    warn(\"IPython.utils.io.raw_print has been deprecated since IPython 7.0\", DeprecationWarning, stacklevel=2)\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()\n\n@undoc\ndef raw_print_err(*args, **kw):\n    \"\"\"DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print().\"\"\"\n    warn(\"IPython.utils.io.raw_print_err has been deprecated since IPython 7.0\", DeprecationWarning, stacklevel=2)\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stderr__)\n    sys.__stderr__.flush()\n", "path": "IPython/utils/io.py"}], "after_files": [{"content": "# encoding: utf-8\n\"\"\"\nIO related utilities.\n\"\"\"\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n\n\nimport atexit\nimport os\nimport sys\nimport tempfile\nfrom pathlib import Path\nfrom warnings import warn\n\nfrom IPython.utils.decorators import undoc\nfrom .capture import CapturedIO, capture_output\n\nclass Tee(object):\n    \"\"\"A class to duplicate an output stream to stdout/err.\n\n    This works in a manner very similar to the Unix 'tee' command.\n\n    When the object is closed or deleted, it closes the original file given to\n    it for duplication.\n    \"\"\"\n    # Inspired by:\n    # http://mail.python.org/pipermail/python-list/2007-May/442737.html\n\n    def __init__(self, file_or_name, mode=\"w\", channel='stdout'):\n        \"\"\"Construct a new Tee object.\n\n        Parameters\n        ----------\n        file_or_name : filename or open filehandle (writable)\n            File that will be duplicated\n        mode : optional, valid mode for open().\n            If a filename was give, open with this mode.\n        channel : str, one of ['stdout', 'stderr']\n        \"\"\"\n        if channel not in ['stdout', 'stderr']:\n            raise ValueError('Invalid channel spec %s' % channel)\n\n        if hasattr(file_or_name, 'write') and hasattr(file_or_name, 'seek'):\n            self.file = file_or_name\n        else:\n            encoding = None if \"b\" in mode else \"utf-8\"\n            self.file = open(file_or_name, mode, encoding=encoding)\n        self.channel = channel\n        self.ostream = getattr(sys, channel)\n        setattr(sys, channel, self)\n        self._closed = False\n\n    def close(self):\n        \"\"\"Close the file and restore the channel.\"\"\"\n        self.flush()\n        setattr(sys, self.channel, self.ostream)\n        self.file.close()\n        self._closed = True\n\n    def write(self, data):\n        \"\"\"Write data to both channels.\"\"\"\n        self.file.write(data)\n        self.ostream.write(data)\n        self.ostream.flush()\n\n    def flush(self):\n        \"\"\"Flush both channels.\"\"\"\n        self.file.flush()\n        self.ostream.flush()\n\n    def __del__(self):\n        if not self._closed:\n            self.close()\n\n\ndef ask_yes_no(prompt, default=None, interrupt=None):\n    \"\"\"Asks a question and returns a boolean (y/n) answer.\n\n    If default is given (one of 'y','n'), it is used if the user input is\n    empty. If interrupt is given (one of 'y','n'), it is used if the user\n    presses Ctrl-C. Otherwise the question is repeated until an answer is\n    given.\n\n    An EOF is treated as the default answer.  If there is no default, an\n    exception is raised to prevent infinite loops.\n\n    Valid answers are: y/yes/n/no (match is not case sensitive).\"\"\"\n\n    answers = {'y':True,'n':False,'yes':True,'no':False}\n    ans = None\n    while ans not in answers.keys():\n        try:\n            ans = input(prompt+' ').lower()\n            if not ans:  # response was an empty string\n                ans = default\n        except KeyboardInterrupt:\n            if interrupt:\n                ans = interrupt\n            print(\"\\r\")\n        except EOFError:\n            if default in answers.keys():\n                ans = default\n                print()\n            else:\n                raise\n\n    return answers[ans]\n\n\ndef temp_pyfile(src, ext='.py'):\n    \"\"\"Make a temporary python file, return filename and filehandle.\n\n    Parameters\n    ----------\n    src : string or list of strings (no need for ending newlines if list)\n        Source code to be written to the file.\n    ext : optional, string\n        Extension for the generated file.\n\n    Returns\n    -------\n    (filename, open filehandle)\n        It is the caller's responsibility to close the open file and unlink it.\n    \"\"\"\n    fname = tempfile.mkstemp(ext)[1]\n    with open(Path(fname), \"w\", encoding=\"utf-8\") as f:\n        f.write(src)\n        f.flush()\n    return fname\n\n\n@undoc\ndef raw_print(*args, **kw):\n    \"\"\"DEPRECATED: Raw print to sys.__stdout__, otherwise identical interface to print().\"\"\"\n    warn(\"IPython.utils.io.raw_print has been deprecated since IPython 7.0\", DeprecationWarning, stacklevel=2)\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stdout__)\n    sys.__stdout__.flush()\n\n@undoc\ndef raw_print_err(*args, **kw):\n    \"\"\"DEPRECATED: Raw print to sys.__stderr__, otherwise identical interface to print().\"\"\"\n    warn(\"IPython.utils.io.raw_print_err has been deprecated since IPython 7.0\", DeprecationWarning, stacklevel=2)\n\n    print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\\n'),\n          file=sys.__stderr__)\n    sys.__stderr__.flush()\n", "path": "IPython/utils/io.py"}]}