我试图通过设置好的管道通过注入的.dll将来自外部进程的一些数据管道传输到我的程序。但是,ReadFile()仅在退出外部程序后才返回(此后它将给出正确的输出)。这是标准行为,还是我在使用管道(或其他方式)错误?
下面是该代码的相关部分(为简洁起见,省略了一些部分):
main.cpp:
int main() {
// Create a duplex pipe-based communication channel
STARTUPINFO startupInfo = {};
HANDLE parent_IN, parent_OUT;
if (!IntraProcessComms(startupInfo, parent_IN, parent_OUT)) {
std::cout << "Could not set up communication necessities" << std::endl;
return 1;
}
// Launch program and obtain the handle
PROCESS_INFORMATION processInfo = {};
if (!CreateProcess(
nullptr, // path
LPSTR("[the program path]"), // commands
nullptr, // handler inheritable
nullptr, // thread inheritable
true, // handler inheritance from caller
0, // creation flag
nullptr, // environment
nullptr, // directory
&startupInfo, // startup info
&processInfo)) { // process info
std::cout << "Could not launch program" << std::endl;
return 2;
}
// Inject the DLL (omitted here; it is injected successfully)
if (!InjectDLL(processInfo.hProcess, "scraper.dll")) {
std::cout << "Could not inject DLL" << std::endl;
return 3;
}
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
std::cout << "Successfully set up" << std::endl;
char buffer[BUFSIZ];
ZeroMemory(buffer, BUFSIZ);
ReadFile(parent_IN, buffer, sizeof(buffer), nullptr, nullptr);
std::cout << "Read: \"" << buffer << "\"" << std::endl;
return 0;
}
bool IntraProcessComms(STARTUPINFO &si, HANDLE &parent_IN, HANDLE &parent_OUT) {
HANDLE child_IN, child_OUT;
SECURITY_ATTRIBUTES securityAttr {
sizeof(SECURITY_ATTRIBUTES), // size
nullptr, // security
true // inheritable
};
// Create pipes from the child to the parent and vice-versa
if (!CreatePipe(
&parent_IN,
&child_OUT,
&securityAttr,
0)
|| !CreatePipe(
&child_IN,
&parent_OUT,
&securityAttr,
0))
return false;
// Ensure only the correct handles are inherited
if (!SetHandleInformation(
parent_IN,
HANDLE_FLAG_INHERIT,
0)
|| !SetHandleInformation(
parent_OUT,
HANDLE_FLAG_INHERIT,
0))
return false;
// Set up startupinfo
si.cb = sizeof(STARTUPINFO);
si.hStdError = child_OUT;
si.hStdOutput = child_OUT;
si.hStdInput = child_IN;
si.dwFlags = STARTF_USESTDHANDLES;
return true;
}
scraper.dll:
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) {
if (fdwReason == DLL_PROCESS_ATTACH) {
// stdout was redirected by IntraProcessComms()
std::cout << "Send from .dll";
}
return true;
}
(可能存在一些明显的错误/奇怪的做法,我是C ++的新手)
答案 0 :(得分:1)
写入std::cout
的内容将在内部缓存,直到缓冲区已满或刷新为止。直到发生刷新,管道才会看到任何写入的数据。
您可以在写入数据后调用std::cout.flush()
,或在输出语句后附加<< std::endl
以添加换行符并刷新缓冲区。如果您仅要发送完整的消息(即,一个<<
到cout
,而不是几个来编写消息),则可以在流中使用unitbuf
标志来刷新输出在每次输出操作(std::cout << std::unitbuf << "Send from .dll";
之后,您可以使用nounitbuf
重新打开缓冲。