Anonymous Pipe ใน Windows เป็น one-way pipe ระหว่าง parent-child process ใช้ CreatePipe() สร้าง แล้ว redirect stdin/stdout ของ child
ขั้นตอนสำคัญ
CreatePipe(&read, &write, &sa, 0)สร้าง pipe พร้อม security attributes ให้สืบทอดได้- ตั้งค่า
STARTUPINFOredirect child's stdin ไปที่ read handle SetHandleInformation(write, HANDLE_FLAG_INHERIT, 0)ห้าม child สืบทอด write handleCreateProcess()สร้าง child process- Parent ปิด read handle, เขียนข้อมูลลง write handle
- Child อ่านจาก stdin (ซึ่งเป็น read handle ของ pipe)
โค้ด Parent Process
HANDLE read, write;
SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, TRUE};
CreatePipe(&read, &write, &sa, 0);
STARTUPINFO si; GetStartupInfo(&si);
si.hStdInput = read; si.dwFlags = STARTF_USESTDHANDLES;
SetHandleInformation(write, HANDLE_FLAG_INHERIT, 0);
CreateProcess(NULL, "child.exe", NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
CloseHandle(read);
WriteFile(write, message, len, &written, NULL);
CloseHandle(write);
WaitForSingleObject(pi.hProcess, INFINITE);
โค้ด Child Process
HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
ReadFile(h, buffer, size, &read, NULL);
printf("Received: %s", buffer);