Skip to content

Commit 6625ac0

Browse files
committed
dispatch: fix logging to a file on Windows
Port the dispatch_debug test to Windows and fix a bug that it found related to logfile initialization. _dispatch_logv_init()'s Windows implementation uses _fdopen() and fprintf() to write the log header. However, this gives ownership of the file to stdio, so fclose() closes the descriptor and causes future writes to trigger CRT assertion failures. Avoid this by using snprintf() and _write() instead.
1 parent dde5892 commit 6625ac0

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/init.c

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -733,15 +733,19 @@ _dispatch_logv_init(void *context DISPATCH_UNUSED)
733733
dispatch_log_basetime = _dispatch_absolute_time();
734734
#endif
735735
#if defined(_WIN32)
736-
FILE *pLogFile = _fdopen(dispatch_logfile, "w");
737-
738736
char szProgramName[MAX_PATH + 1] = {0};
739737
GetModuleFileNameA(NULL, szProgramName, MAX_PATH);
740738

741-
fprintf(pLogFile, "=== log file opened for %s[%lu] at "
742-
"%ld.%06u ===\n", szProgramName, GetCurrentProcessId(),
743-
tv.tv_sec, (int)tv.tv_usec);
744-
fclose(pLogFile);
739+
char szMessage[512];
740+
int len = snprintf(szMessage, sizeof(szMessage),
741+
"=== log file opened for %s[%lu] at %ld.%06u ===",
742+
szProgramName, GetCurrentProcessId(), tv.tv_sec,
743+
(int)tv.tv_usec);
744+
if (len > 0) {
745+
len = MIN(len, sizeof(szMessage) - 1);
746+
_write(dispatch_logfile, szMessage, len);
747+
_write(dispatch_logfile, "\n", 1);
748+
}
745749
#else
746750
dprintf(dispatch_logfile, "=== log file opened for %s[%u] at "
747751
"%ld.%06u ===\n", getprogname() ?: "", getpid(),

tests/dispatch_debug.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@
3131
int
3232
main(void)
3333
{
34+
#if defined(_WIN32)
35+
_putenv_s("LIBDISPATCH_LOG", "stderr");
36+
#else
3437
setenv("LIBDISPATCH_LOG", "stderr", 1); // rdar://problem/8493990
38+
#endif
3539
dispatch_test_start("Dispatch Debug");
3640

3741
dispatch_queue_t main_q = dispatch_get_main_queue();

0 commit comments

Comments
 (0)