Skip to content

Commit c026885

Browse files
committed
Merge branch 'winprint' into 'master'
Capture stdout on Windows Closes #211 See merge request lfortran/lfortran!642
2 parents 1bb4ae0 + bc2f4bf commit c026885

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

src/lfortran/fortran_kernel.cpp

+18-9
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,14 @@
33
#include <stdio.h>
44
#include <stdlib.h>
55

6-
#ifndef _WIN32
6+
#ifdef _WIN32
7+
# include <io.h>
8+
# define fileno _fileno
9+
# define dup _dup
10+
# define dup2 _dup2
11+
# define close _close
12+
# include <fcntl.h>
13+
#else
714
# include <unistd.h>
815
#endif
916

@@ -30,33 +37,35 @@ namespace LFortran
3037
{
3138
public:
3239
RedirectStdout(std::string &out) : _out{out} {
33-
#ifndef _WIN32
40+
stdout_fileno = fileno(stdout);
3441
std::cout << std::flush;
3542
fflush(stdout);
36-
saved_stdout = dup(STDOUT_FILENO);
37-
if(pipe(out_pipe) != 0) {
43+
saved_stdout = dup(stdout_fileno);
44+
#ifdef _WIN32
45+
if (_pipe(out_pipe, 65536, O_BINARY) != 0) {
46+
#else
47+
if (pipe(out_pipe) != 0) {
48+
#endif
3849
throw LFortranException("pipe() failed");
3950
}
40-
dup2(out_pipe[1], STDOUT_FILENO);
51+
dup2(out_pipe[1], stdout_fileno);
4152
close(out_pipe[1]);
4253
printf("X");
43-
#endif
4454
}
4555

4656
~RedirectStdout() {
47-
#ifndef _WIN32
4857
fflush(stdout);
4958
read(out_pipe[0], buffer, MAX_LEN);
50-
dup2(saved_stdout, STDOUT_FILENO);
59+
dup2(saved_stdout, stdout_fileno);
5160
_out = std::string(&buffer[1]);
52-
#endif
5361
}
5462
private:
5563
std::string &_out;
5664
static const size_t MAX_LEN=1024;
5765
char buffer[MAX_LEN+1] = {0};
5866
int out_pipe[2];
5967
int saved_stdout;
68+
int stdout_fileno;
6069
};
6170

6271
class custom_interpreter : public xeus::xinterpreter

0 commit comments

Comments
 (0)