bpo-17852: Maintain a list of BufferedWriter objects. Flush them on exit. (#1908)
* Maintain a list of BufferedWriter objects. Flush them on exit.
In Python 3, the buffer and the underlying file object are separate
and so the order in which objects are finalized matters. This is
unlike Python 2 where the file and buffer were a single object and
finalization was done for both at the same time. In Python 3, if
the file is finalized and closed before the buffer then the data in
the buffer is lost.
This change adds a doubly linked list of open file buffers. An atexit
hook ensures they are flushed before proceeding with interpreter
shutdown. This is addition does not remove the need to properly close
files as there are other reasons why buffered data could get lost during
finalization.
Initial patch by Armin Rigo.
* Use weakref.WeakSet instead of WeakKeyDictionary.
* Simplify buffered double-linked list types.
* In _flush_all_writers(), suppress errors from flush().
* Remove NEWS entry, use blurb.
diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c
index 189b1cd..50c87c1 100644
--- a/Modules/_io/bufferedio.c
+++ b/Modules/_io/bufferedio.c
@@ -196,7 +196,7 @@
}
-typedef struct {
+typedef struct _buffered {
PyObject_HEAD
PyObject *raw;
@@ -240,8 +240,18 @@
PyObject *dict;
PyObject *weakreflist;
+
+ /* a doubly-linked chained list of "buffered" objects that need to
+ be flushed when the process exits */
+ struct _buffered *next, *prev;
} buffered;
+/* the actual list of buffered objects */
+static buffered buffer_list_end = {
+ .next = &buffer_list_end,
+ .prev = &buffer_list_end
+};
+
/*
Implementation notes:
@@ -387,6 +397,15 @@
static void
+remove_from_linked_list(buffered *self)
+{
+ self->next->prev = self->prev;
+ self->prev->next = self->next;
+ self->prev = NULL;
+ self->next = NULL;
+}
+
+static void
buffered_dealloc(buffered *self)
{
self->finalizing = 1;
@@ -394,6 +413,8 @@
return;
_PyObject_GC_UNTRACK(self);
self->ok = 0;
+ if (self->next != NULL)
+ remove_from_linked_list(self);
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *)self);
Py_CLEAR(self->raw);
@@ -1817,10 +1838,33 @@
self->fast_closed_checks = (Py_TYPE(self) == &PyBufferedWriter_Type &&
Py_TYPE(raw) == &PyFileIO_Type);
+ if (self->next == NULL) {
+ self->prev = &buffer_list_end;
+ self->next = buffer_list_end.next;
+ buffer_list_end.next->prev = self;
+ buffer_list_end.next = self;
+ }
+
self->ok = 1;
return 0;
}
+/*
+* Ensure all buffered writers are flushed before proceeding with
+* normal shutdown. Otherwise, if the underlying file objects get
+* finalized before the buffered writer wrapping it then any buffered
+* data will be lost.
+*/
+void _PyIO_atexit_flush(void)
+{
+ while (buffer_list_end.next != &buffer_list_end) {
+ buffered *buf = buffer_list_end.next;
+ remove_from_linked_list(buf);
+ buffered_flush(buf, NULL);
+ PyErr_Clear();
+ }
+}
+
static Py_ssize_t
_bufferedwriter_raw_write(buffered *self, char *start, Py_ssize_t len)
{