diff --git a/api/boinc_api.cpp b/api/boinc_api.cpp
index 1f8e026..d0c09ad 100644
--- a/api/boinc_api.cpp
+++ b/api/boinc_api.cpp
@@ -660,6 +660,11 @@ void boinc_exit(int status) {
     BOINCINFO("Exit Status: %d", status);
     fflush(NULL);
 
+    // Ensure redirected stderr file is written to disk; fflush is
+    // insufficient
+    if (diagnostics_is_flag_set(BOINC_DIAG_REDIRECTSTDERR))
+        boinc_flush(stderr);
+
 #if defined(_WIN32)
     // Halt all the threads and clean up.
     TerminateProcess(GetCurrentProcess(), status);
diff --git a/lib/filesys.cpp b/lib/filesys.cpp
index 015749d..2e12238 100644
--- a/lib/filesys.cpp
+++ b/lib/filesys.cpp
@@ -480,6 +480,13 @@ FILE* boinc_fopen(const char* path, const char* mode) {
     return f;
 }
 
+int boinc_flush(FILE* f) {
+#ifdef _WIN32
+    return _commit(fileno(f));
+#else
+    return fsync(fileno(f));
+#endif /* _WIN32 */
+}
 
 int boinc_file_exists(const char* path) {
     struct stat buf;
diff --git a/lib/filesys.h b/lib/filesys.h
index b5a14cd..3a43292 100644
--- a/lib/filesys.h
+++ b/lib/filesys.h
@@ -46,6 +46,7 @@ extern "C" {
   extern int boinc_delete_file(const char*);
   extern int boinc_touch_file(const char *path);
   extern FILE* boinc_fopen(const char* path, const char* mode);
+  extern int boinc_flush(FILE*);
   extern int boinc_copy(const char* orig, const char* newf);
   extern int boinc_rename(const char* old, const char* newf);
   extern int boinc_mkdir(const char*);
