Цитата(нуп @ 2.6.2012, 11:59 ) | | Ошибку пишет 183. |
Цитата(нуп @ 2.6.2012, 11:59 ) | | startup.hStdOutput = pipe_stdout_read; |
Цитата(feodorv @ 1.6.2012, 18:51 ) | | startup.hStdInput = pipe_stdin_read; // another pipe |
Цитата(feodorv @ 1.6.2012, 13:48 ) | | Можно же в посковиках забить одновременно поиск по CreatePipe и CreateProcess и посмотреть примеры |
| Код | /* This sample program demonstrates STDIN/STDOUT redirection of a child 16-bit process. The program starts an utility, that just reverses all characters in the lines (extracted from STDIN) and writes "reversed" content to STDOUT. I redirect STDIN by anonymous pipe and pass several lines to the child process, simulating usual input. I redirect STDOUT by anonuymous pipe and grab all output generated by child process. й Kid_Deceiver */ #include <windows.h> #include <stdio.h> char sysmsg[512]; /* GetSysMsg retruns text description of given error code */ char* GetSysMsg( DWORD errcode ) { FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, // don't use arguments NULL, // don't use format string errcode, // error code 0, // any language sysmsg, sizeof(sysmsg), // message buffer NULL); // no additional arguments return( sysmsg ); } int main() { int i; DWORD written, read, err; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; HANDLE hReadOut; // pipe handles for redirecting STDOUT HANDLE hWriteOut; HANDLE hReadIn; // pipe handles for redirecting STDIN HANDLE hWriteIn; char buf[255]; char *a[] = { ",tnemom dna hctip taerg fo sesirpretne dnA\n", ",yrwa nrut stnerruc rieht drager siht htiW\n", ".noitca fo eman eht esol dnA\n", "\n" }; // Prepare security attributes for pipes. // Note - inheritance flag is ON! memset( &sa, 0, sizeof(sa) ); sa.nLength = sizeof( sa ); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; // Create pipe for output redirection if (!CreatePipe( &hReadOut, // read end of the pipr &hWriteOut, // write end of the pipe &sa, // security attributes 0) ) { // bytes reserved - default 0 err = GetLastError(); fprintf( stderr, "output pipe creation failed (%d) - %s\n", err, GetSysMsg( err ) ); exit( 1 ); } // Create pipe for input redirection. if (!CreatePipe( &hReadIn, &hWriteIn, &sa, 0 ) ) { err = GetLastError(); fprintf( stderr, "input pipe creation failed (%d) - %s\n", err, GetSysMsg( err ) ); CloseHandle( hReadOut ); CloseHandle( hWriteOut ); exit( 1 ); } // Prepare child process startup data // Force child process to use hWriteOut as stdout and hReadIn as stdin memset( &si, 0, sizeof(si) ); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.wShowWindow = SW_HIDE; si.hStdInput = hReadIn; si.hStdOutput = hWriteOut; si.hStdError = hWriteOut; // Spawn child process. if (!CreateProcess( NULL, "util.exe", // command line NULL, NULL, // security TRUE, // inherit parent handles 0, NULL, NULL, // flags, env, curr. dir &si, &pi )) { // startup and result err = GetLastError(); fprintf( stderr, "CreateFile failed (%d) - %s\n", err, GetSysMsg( err ) ); CloseHandle( hReadOut ); CloseHandle( hWriteOut ); CloseHandle( hReadIn ); CloseHandle( hWriteIn ); exit( 1 ); } // Close pipe ends, which we're not going to use CloseHandle( hWriteOut ); // child process will write here CloseHandle( hReadIn ); // child process will read here // Write some input data for the child process for (i = 0; i < (sizeof(a)/sizeof(a[0])); i++) { WriteFile( hWriteIn, a[i], strlen(a[i]), &written, NULL ); } // Read process output. while( TRUE ) { if ( !ReadFile( hReadOut, // handle of the read end of our pipe buf, // address of buffer that receives data sizeof(buf)-1, // number of bytes to read &read, // number of bytes really read NULL ) ) { // non-overlapped. err = GetLastError(); fprintf( stderr, "output pipe read error (%d) - %s\n", err, GetSysMsg( err ) ); // It might be "normal" error. Spawned app just closed the // stdout, and in this case ReadFile returned FALSE. break; } // Test for the "normal" end of the output if (0 == read) { break; // nothing to read, child processs has closed the output } // Write all data from redirected stdout to our own stdout. buf[ read ] = 0; fprintf( stdout, "%s", buf ); } // Close all remaining handles CloseHandle (pi.hProcess); CloseHandle (pi.hThread ); CloseHandle( hReadOut ); CloseHandle( hWriteIn ); return 0; } /* This program reads lines from standard input, changes characters of each line to reverse order, then writes the "reversed" line to stdandard output. The program terminates if: a) EOF occurs in stdin; b) empty line (not counting newline character) found. Built by TC 3.0, 16-bit, small memory model. Executable file UTIL.EXE. */ #include <stdio.h> #include <string.h> int main() { char *pc, line[16384]; while( pc = fgets( line, sizeof(line), stdin ) ) { strrev( pc ); if ('\n' == pc[0]) pc++; if (0 == strlen(pc)) break; fprintf( stdout, "%s\n", pc ); } return 0; }
|
| Код | //------------Пример использования CreateProcess и Anonymous Pipes----------- // childspawn.cpp // Приложение запускает shell и перехватывает его ввод/вывод //---------------------use freely-------------------------------------------- #include <windows.h> #include <stdio.h> #include <conio.h> #include <string.h> #pragma hdrstop #include <condefs.h>
#define bzero(a) memset(a,0,sizeof(a)) //для сокращения писанины
bool IsWinNT() //проверка запуска под NT { OSVERSIONINFO osv; osv.dwOSVersionInfoSize = sizeof(osv); GetVersionEx(&osv); return (osv.dwPlatformId == VER_PLATFORM_WIN32_NT); }
void ErrorMessage(char *str) //вывод подробной информации об ошибке { LPVOID msg; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // язык по умолчанию (LPTSTR) &msg, 0, NULL ); printf("%s: %s\n",str,msg); LocalFree(msg); }
//--------------------------------------------------------------------------- void main() { char buf[1024]; //буфер ввода/вывода
STARTUPINFO si; SECURITY_ATTRIBUTES sa; SECURITY_DESCRIPTOR sd; //структура security для пайпов PROCESS_INFORMATION pi; HANDLE newstdin,newstdout,read_stdout,write_stdin; //дескрипторы пайпов
if (IsWinNT()) //инициализация security для Windows NT { InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, true, NULL, false); sa.lpSecurityDescriptor = &sd; } else sa.lpSecurityDescriptor = NULL; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = true; //разрешаем наследование дескрипторов
if (!CreatePipe(&newstdin,&write_stdin,&sa,0)) //создаем пайп для stdin { ErrorMessage("CreatePipe"); getch(); return; } if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) //создаем пайп для stdout { ErrorMessage("CreatePipe"); getch(); CloseHandle(newstdin); CloseHandle(write_stdin); return; }
GetStartupInfo(&si); //создаем startupinfo для дочернего процесса /* Параметр dwFlags сообщает функции CreateProcess как именно надо создать процесс. STARTF_USESTDHANDLES управляет полями hStd*. STARTF_USESHOWWINDOW управляет полем wShowWindow. */ si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdOutput = newstdout; si.hStdError = newstdout; //подменяем дескрипторы для дочернего процесса si.hStdInput = newstdin; char app_spawn[] = "d:\\winnt\\system32\\cmd.exe"; //это просто пример, //замените на то, что вам нужно
//создаем дочерний процесс if (!CreateProcess(app_spawn,NULL,NULL,NULL,TRUE,CREATE_NEW_CONSOLE, NULL,NULL,&si,&pi)) { ErrorMessage("CreateProcess"); getch(); CloseHandle(newstdin); CloseHandle(newstdout); CloseHandle(read_stdout); CloseHandle(write_stdin); return; }
unsigned long exit=0; //код завершения процесса unsigned long bread; //кол-во прочитанных байт unsigned long avail; //кол-во доступных байт
bzero(buf); for(;;) //основной цикл программы { GetExitCodeProcess(pi.hProcess,&exit); //пока дочерний процесс не закрыт if (exit != STILL_ACTIVE) break; PeekNamedPipe(read_stdout,buf,1023,&bread,&avail,NULL); //Проверяем, есть ли данные для чтения в stdout if (bread != 0) { bzero(buf); if (avail > 1023) { while (bread >= 1023) { ReadFile(read_stdout,buf,1023,&bread,NULL); //читаем из пайпа stdout printf("%s",buf); bzero(buf); } } else { ReadFile(read_stdout,buf,1023,&bread,NULL); printf("%s",buf); } } if (kbhit()) //проверяем, введено ли что-нибудь с клавиатуры { bzero(buf); *buf = (char)getche(); //printf("%c",*buf); WriteFile(write_stdin,buf,1,&bread,NULL); //отправляем это в stdin if (*buf == '\r') { *buf = '\n'; printf("%c",*buf); WriteFile(write_stdin,buf,1,&bread,NULL); //формирум конец строки, //если нужно } } } CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(newstdin); //небольшая уборка за собой CloseHandle(newstdout); CloseHandle(read_stdout); CloseHandle(write_stdin); } //----------------------------EOF-------------------------------------------- //---------------------------------------------------------------------------
|
Цитата(xvr @ 2.6.2012, 19:40 ) | | WaitForSingleObject - выкинуть |
Цитата(feodorv @ 1.6.2012, 13:48 ) | | Тогда нужно читать из пайпа до получения ошибки или какого-то признака, что php закончило вывод. |
|