| 301 | } |
| 302 | |
| 303 | void redirect(int port) |
| 304 | { |
| 305 | HANDLE readStdPipe = NULL, writeStdPipe = NULL; |
| 306 | |
| 307 | SECURITY_ATTRIBUTES saAttr; |
| 308 | saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); |
| 309 | saAttr.bInheritHandle = TRUE; |
| 310 | saAttr.lpSecurityDescriptor = nullptr; |
| 311 | |
| 312 | CreatePipe(&readStdPipe, &writeStdPipe, &saAttr, 0); |
| 313 | |
| 314 | const auto oldStdout = _dup(_fileno(stdout)); |
| 315 | const auto oldStderr = _dup(_fileno(stderr)); |
| 316 | |
| 317 | if (oldStdout == -1 || oldStderr == -1) |
| 318 | { |
| 319 | printf("stdout or stderr redirect error"); |
| 320 | if (oldStdout != -1) |
| 321 | { |
| 322 | _close(oldStdout); |
| 323 | } |
| 324 | if (oldStderr != -1) |
| 325 | { |
| 326 | _close(oldStderr); |
| 327 | } |
| 328 | |
| 329 | return; |
| 330 | } |
| 331 | |
| 332 | const auto stream = _open_osfhandle(reinterpret_cast<long>(writeStdPipe), 0); |
| 333 | FILE* capture = nullptr; |
| 334 | if (stream == -1) |
| 335 | { |
| 336 | printf("capture stream open fail"); |
| 337 | _dup2(oldStdout, _fileno(stdout)); |
| 338 | _dup2(oldStderr, _fileno(stderr)); |
| 339 | |
| 340 | _close(oldStdout); |
| 341 | _close(oldStderr); |
| 342 | |
| 343 | return; |
| 344 | } |
| 345 | capture = _fdopen(stream, "wt"); |
| 346 | |
| 347 | // stdout now refers to file "capture" |
| 348 | if (_dup2(_fileno(capture), _fileno(stdout)) == -1) |
| 349 | { |
| 350 | printf("Can't _dup2 stdout to capture"); |
| 351 | |
| 352 | _dup2(oldStdout, _fileno(stdout)); |
| 353 | _dup2(oldStderr, _fileno(stderr)); |
| 354 | |
| 355 | _close(oldStdout); |
| 356 | _close(oldStderr); |
| 357 | |
| 358 | return; |
| 359 | } |
| 360 |
no test coverage detected