Last active
February 16, 2023 20:35
-
-
Save skeeto/5b8d5f0e525218c3a9ad35f9727afe4f to your computer and use it in GitHub Desktop.
Win32 piped child example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $ cc -nostartfiles -o child.exe child.c | |
// $ cl child.c /link /subsystem:console kernel32.lib | |
#define WIN32_LEAN_AND_MEAN | |
#include <windows.h> | |
int mainCRTStartup(void) | |
{ | |
HANDLE stdin = GetStdHandle(STD_INPUT_HANDLE); | |
HANDLE stdout = GetStdHandle(STD_OUTPUT_HANDLE); | |
for (;;) { | |
char buf[8]; // deliberately small to force multiple iterations | |
DWORD len = sizeof(buf); | |
if (!ReadFile(stdin, buf, len, &len, 0)) { | |
break; | |
} | |
WriteFile(stdout, buf, len, &len, 0); | |
} | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $ cc -nostartfiles -o parent.exe parent.c | |
// $ cl parent.c /link /subsystem:console kernel32.lib | |
#define WIN32_LEAN_AND_MEAN | |
#include <windows.h> | |
int mainCRTStartup(void) | |
{ | |
HANDLE stdin[2]; | |
HANDLE stdout[2]; | |
CreatePipe(stdin+0, stdin+1, 0, 0); | |
CreatePipe(stdout+0, stdout+1, 0, 0); | |
SetHandleInformation(stdin[0], HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); | |
SetHandleInformation(stdout[1], HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); | |
STARTUPINFOW si = {0}; | |
si.cb = sizeof(si); | |
si.hStdInput = stdin[0]; | |
si.hStdOutput = stdout[1]; | |
si.hStdError = GetStdHandle(STD_ERROR_HANDLE); | |
si.dwFlags |= STARTF_USESTDHANDLES; | |
PROCESS_INFORMATION pi; | |
CreateProcessW(L"child.exe", L"child", 0, 0, TRUE, 0, 0, 0, &si, &pi); | |
CloseHandle(pi.hThread); | |
CloseHandle(stdin[0]); | |
CloseHandle(stdout[1]); | |
char msg[] = "hello world this is a test\n"; | |
DWORD len = sizeof(msg) - 1; | |
WriteFile(stdin[1], msg, len, &len, 0); | |
CloseHandle(stdin[1]); | |
for (;;) { | |
char buf[8]; // deliberately small to force multiple iterations | |
DWORD len = sizeof(buf); | |
if (!ReadFile(stdout[0], buf, len, &len, 0)) { | |
break; | |
} | |
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, len, &len, 0); | |
} | |
CloseHandle(stdin[0]); | |
WaitForSingleObject(pi.hProcess, INFINITE); | |
CloseHandle(pi.hProcess); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment