作者CMJ0121 (請多指教!!)
看板C_and_CPP
標題[問題] CreatePipe & 程式間傳送訊息的問題
時間Sat Oct 17 20:53:58 2009
Q: 我想自己寫一個程式 A, 用 CreateProcess 開啟 telnet
然後想用 CreatePipe建立管線 使得 A <-> telnet 可以溝通
目前我已經可以成功建立 telnet
CreatePipe也沒有出現 Error
但是我用 WriteFile卻沒辦法跟 telnet溝通
(我用來登入 ptt, 但是沒有出現任何反應)
所以我先建立 cmd.exe來測試
然後用 WriteFile出來之後 cmd.exe沒有如我預期般的出現 test字眼...
/* ================== 我的原始碼 ======================= */
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
int main( int argc, TCHAR *argv[] )
{
int len;
HANDLE telnet_input, telnt_output;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( !CreateProcess( NULL, // No module name (use command line)
"cmd.exe", // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return 1;
}
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if( !CreatePipe( &pi.hProcess, &telnet_input, &sa, 0 ) )
{
printf("Create pipe failed (%d).\n", GetLastError() );
return 1;
}
WriteFile( telnet_input, "test", 4, &len, NULL );
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
CloseHandle( telnet_input );
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.112.45.253
1F:推 suhorng:哇噢 ... 你的順序怪怪的ˊˋ 首先 Pipe 要在 CreateProc- 10/17 22:08
2F:→ suhorng:ess之前就先建立好,然後設定 sa, 讓子程序繼承 telnet_o- 10/17 22:09
3F:→ suhorng:utput Handle, 才能用來跟子程序溝通. 然後 dwFlags 要設 10/17 22:10
4F:→ suhorng:定STARTF_USESTDHANDLES, hStdInput hStdOutput hStdError 10/17 22:11
5F:→ suhorng:都各要一個 Pipe 這樣(或許 hStdOutput, hStdError 可以 10/17 22:11
6F:→ suhorng:使用同一個 Pipe) 10/17 22:11
7F:推 holymars:或者是考慮用NamedPipe 10/18 00:02
8F:→ CMJ0121:感謝1F大大熱情教學! 不過我想問我可以只改 input不改 10/18 00:33
9F:→ CMJ0121:output嗎?? 10/18 00:33