[問題] CreatePipe & 程式間傳送訊息的問題

看板C_and_CPP (C/C++)作者 (請多指教!!)時間16年前 (2009/10/17 20:54), 編輯推噓2(207)
留言9則, 3人參與, 最新討論串1/1
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

10/17 22:08, , 1F
哇噢 ... 你的順序怪怪的ˊˋ 首先 Pipe 要在 CreateProc-
10/17 22:08, 1F

10/17 22:09, , 2F
ess之前就先建立好,然後設定 sa, 讓子程序繼承 telnet_o-
10/17 22:09, 2F

10/17 22:10, , 3F
utput Handle, 才能用來跟子程序溝通. 然後 dwFlags 要設
10/17 22:10, 3F

10/17 22:11, , 4F
定STARTF_USESTDHANDLES, hStdInput hStdOutput hStdError
10/17 22:11, 4F

10/17 22:11, , 5F
都各要一個 Pipe 這樣(或許 hStdOutput, hStdError 可以
10/17 22:11, 5F

10/17 22:11, , 6F
使用同一個 Pipe)
10/17 22:11, 6F

10/18 00:02, , 7F
或者是考慮用NamedPipe
10/18 00:02, 7F

10/18 00:33, , 8F
感謝1F大大熱情教學! 不過我想問我可以只改 input不改
10/18 00:33, 8F

10/18 00:33, , 9F
output嗎??
10/18 00:33, 9F
文章代碼(AID): #1AsRvfPc (C_and_CPP)
文章代碼(AID): #1AsRvfPc (C_and_CPP)