예제 #1
0
Process::ProcessImpl::ProcessImpl(const std::string& cmd, const std::vector<std::string>& argv) :
    m_free(false)
{
    std::string args;
    for (unsigned int i = 0; i < argv.size(); ++i) {
        args += argv[i];
        if (i + 1 < argv.size())
            args += ' ';
    }

    ZeroMemory(&m_startup_info, sizeof(STARTUPINFO));
    m_startup_info.cb = sizeof(STARTUPINFO);
    ZeroMemory(&m_process_info, sizeof(PROCESS_INFORMATION));

    if (!CreateProcess(const_cast<char*>(cmd.c_str()), const_cast<char*>(args.c_str()), 0, 0, false, 
        CREATE_NO_WINDOW, 0, 0, &m_startup_info, &m_process_info)) {
            std::string err_str;
            DWORD err = GetLastError();
            DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM;
            LPSTR buf;
            if (FormatMessageA(flags, 0, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, 0)) {
                err_str += buf;
                LocalFree(buf);
            }
            throw std::runtime_error("Process::Process : Failed to create child process.  Windows error was: \"" + err_str + "\"");
        }
        WaitForInputIdle(m_process_info.hProcess, 1000); // wait for process to finish setting up, or for 1 sec, which ever comes first
}
STDMETHODIMP CShellExt::SendToWindow(HANDLE hProcess, LPCSTR pszText)
{
    //Wait for the process to be ready to accept input
    WaitForInputIdle(hProcess, INFINITE);
    CSendKeys sk;
    sk.SendKeys(pszText);
    return NOERROR;
}
예제 #3
0
WaitResult System::WaitInputIdle( const HProcess & hProcess, UInt iMilliseconds ) const
{
    DWord dwResult = WaitForInputIdle( hProcess.m_hThreadingObject, (DWord)iMilliseconds );
    if ( dwResult == 0 )
        return WAIT_OK;
    if ( dwResult == WAIT_TIMEOUT )
        return WAIT_EXPIRED;
    return WAIT_ERROR;
}
예제 #4
0
//通过匿名管道连接引擎引擎
bool CEngine::LinkEngineWithUnnamed()
{
	status = 0;//引擎连接未就绪

	SECURITY_ATTRIBUTES sa;
	sa.nLength=sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor=NULL;//Default security attributes
	sa.bInheritHandle= TRUE;//handle can be inherited

	if(!CreatePipe(&pde.engine_read,&pde.platform_write,&sa,BUFSIZE) ||!CreatePipe(&pde.platform_read,&pde.engine_write,&sa,BUFSIZE))//创建两个平台与引擎之间互相通信的匿名管道
	{
		ErrorBox("CreatePipe failed");
		return false;
	}

	char Filter[]="(exe files)|*.exe|(all files)|*.*||";//文件滤镜	
	CFileDialog FileName(true,NULL,NULL,Filter,NULL,gameSet.EngineInitDir);//定义文件对话框类实例
	if(FileName.DoModal()==IDOK)
	{
		path=FileName.GetFilePath();
		LPCTSTR folder=FileName.GetFolderPath(path);
		char EngineDir[MAX_PATH]={0};
		strcpy(EngineDir,folder);
				
		STARTUPINFO si;
		PROCESS_INFORMATION pi;
		ZeroMemory(&si,sizeof(si));
		si.cb=sizeof(si);
		si.dwFlags=STARTF_USESHOWWINDOW |STARTF_USESTDHANDLES;
		si.wShowWindow=SW_HIDE;
		si.hStdInput=pde.engine_read;
		si.hStdOutput=pde.engine_write;
		si.hStdError=pde.engine_write;
		if(!CreateProcess(path,"",NULL,NULL,true,0,NULL,EngineDir,&si,&pi))//打开引擎进程
		{
			ErrorBox("CreateProcess failed");
			status = -1;
			return false;
		}
		CloseHandle(pde.engine_read);
		CloseHandle(pde.engine_write);
		WaitForInputIdle(pi.hProcess,INFINITE);
		pde.hEProcess = pi.hProcess;
		CloseHandle(pi.hThread);
		SetCurrentDirectory(gameSet.CurDir);//恢复当前主应用程序的进程
		CreateEngineInfoBoard();
	}
	else
	{
		status = -1;
		return false;
	}

	return true;
}
예제 #5
0
bool CCommonAppUtils::LaunchApplication
    ( const CString& sCommandLine
    , UINT idErrMessageFormat
    , bool bWaitForStartup
    , bool bWaitForExit
    , HANDLE hWaitHandle)
{
    PROCESS_INFORMATION process;

    // make sure we get a writable copy of the command line

    size_t bufferLen = sCommandLine.GetLength()+1;
    std::unique_ptr<TCHAR[]> cleanCommandLine (new TCHAR[bufferLen]);
    memcpy (cleanCommandLine.get(),
            (LPCTSTR)sCommandLine,
            sizeof (TCHAR) * bufferLen);

    if (!CCreateProcessHelper::CreateProcess(NULL, cleanCommandLine.get(), sOrigCWD, &process))
    {
        if(idErrMessageFormat != 0)
        {
            CFormatMessageWrapper errorDetails;
            CString msg;
            msg.Format(idErrMessageFormat, (LPCTSTR)errorDetails);
            CString title;
            title.LoadString(IDS_APPNAME);
            MessageBox(NULL, msg, title, MB_OK | MB_ICONINFORMATION);
        }
        return false;
    }
    AllowSetForegroundWindow(process.dwProcessId);

    if (bWaitForStartup)
        WaitForInputIdle(process.hProcess, 10000);

    if (bWaitForExit)
    {
        DWORD count = 1;
        HANDLE handles[2];
        handles[0] = process.hProcess;
        if (hWaitHandle)
        {
            count = 2;
            handles[1] = hWaitHandle;
        }
        WaitForMultipleObjects(count, handles, FALSE, INFINITE);
        if (hWaitHandle)
            CloseHandle(hWaitHandle);
    }

    CloseHandle(process.hThread);
    CloseHandle(process.hProcess);

    return true;
}
예제 #6
0
int ActivePet::launch(std::wstring exePath, std::wstring originalDocPath){

	wchar_t commandLine[4096] = { '\0' };
	if (originalDocPath != L"") {

		// Build the command line.
	    std::wstring editableDocPath = edit(originalDocPath);
		wcscat(commandLine, L"\"");
		wcscat(commandLine, exePath.c_str());
		wcscat(commandLine, L"\" \"");
		wcscat(commandLine, editableDocPath.c_str());
		wcscat(commandLine, L"\"");
	}
    auto_close<void*, &::DestroyEnvironmentBlock> environment(NULL);
	if (!CreateEnvironmentBlock(&environment, m_session.get(), FALSE)) {
        printf("CreateEnvironmentBlock() failed: %d", GetLastError());
		return -30;
	}
    STARTUPINFO si = { sizeof(STARTUPINFO) };
    PROCESS_INFORMATION pi = {};
	if (!CreateProcessAsUser(m_session.get(),
							 exePath.c_str(),
							 commandLine,
							 NULL,
							 NULL,
							 FALSE,
							 CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE,
							 environment.get(),
							 NULL, // lpCurrentDirectory,
							 &si,
							 &pi)) {
        printf("CreateProcessAsUser() failed: %d", GetLastError());
		return -30;
	}
	if (!AssignProcessToJobObject(m_job.get(), pi.hProcess)) {
        printf("AssignProcessToJobObject() failed: %d", GetLastError());
		return -30;
	}
	if (!ResumeThread(pi.hThread)) {
        printf("ResumeThread() failed: %d", GetLastError());
		return -30;
	}
    if (WaitForInputIdle(pi.hProcess, INFINITE) != ERROR_SUCCESS) {
        printf("WaitForInputIdle() failed: %d", GetLastError());
		return -30;
	}
    InjectAndCall(pi.hProcess, "ApplyHooks", 10000);
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);

    return 0;
}
예제 #7
0
STATIC int ExecuteTarget(LPTSTR lpCmdLine)
{
	HWND hWnd = NULL;
	// DWORD dwExitCode = ERROR_SUCCESS;
	PROCESS_INFORMATION pi = { 0 };
	STARTUPINFO si = { sizeof(STARTUPINFO), 0 };
	
	/* Execute the process */
	if (CreateProcess(
		NULL,	/* No module name (use command line) */
		lpCmdLine,	/* Command line */
		NULL,	/* Process handle not inheritable */
		NULL,	/* Thread handle not inheritable */
		FALSE,	/* Set handle inheritance to FALSE */
		0,	/* No creation flags */
		NULL,	/* Use parent's environment block */
		NULL,	/* Use parent's starting directory */
		&si,	/* Pointer to STARTUPINFO structure */
		&pi	/* Pointer to PROCESS_INFORMATION structure */
	)) {
		DWORD dwProcessId = 0;
		
		/* Wait until target executable has finished its initialization */
		WaitForInputIdle(pi.hProcess, INFINITE);

		/* Find target executable window */
		hWnd = GetTopWindow(0);
		while(hWnd != NULL) {
			GetWindowThreadProcessId(hWnd, &dwProcessId);
			if (dwProcessId == pi.dwProcessId) {
				/* And move it to the top. */
				SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
				break;
			}
			hWnd = GetNextWindow(hWnd, GW_HWNDNEXT);
		}

		/* Wait until target executable exits. */
		// Nah
		//WaitForSingleObject(pi.hProcess, INFINITE);
		//GetExitCodeProcess(pi.hProcess, &dwExitCode);

		/* Close process and thread handles. */
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
	} else {
		FatalError(ERROR_SUCCESS, _T("Failed to execute cmdline: %s"), lpCmdLine);
		xfree(lpCmdLine);
	}
	
	return ERROR_SUCCESS;
}
예제 #8
0
파일: misc.c 프로젝트: nohuhu/TuTTY
HWND launch_putty(int action, char *path)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    DWORD wait;
    HWND pwin;
    struct process_record *pr;
    char buf[BUFSIZE];

    memset(&si, 0, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);

    memset(&pi, 0, sizeof(PROCESS_INFORMATION));

    sprintf(buf, "%s -%s \"%s\"", config->putty_path,
	    action ? "edit" : "load", path);

    if (!CreateProcess(config->putty_path, buf, NULL, NULL,
		       FALSE, 0, NULL, NULL, &si, &pi))
	return NULL;

    wait = WaitForInputIdle(pi.hProcess, LAUNCH_TIMEOUT);

    if (wait != 0) {
	CloseHandle(pi.hProcess);
	CloseHandle(pi.hThread);
	return NULL;
    };

    CloseHandle(pi.hThread);

    pwin = NULL;
    EnumThreadWindows(pi.dwThreadId, FindPuttyWindowCallback, (LPARAM) &pwin);

    if (!pwin) {
	CloseHandle(pi.hProcess);
	return NULL;
    };

    pr = (struct process_record *) malloc(sizeof(struct process_record));
    pr->pid = pi.dwProcessId;
    pr->tid = pi.dwThreadId;
    pr->hprocess = pi.hProcess;
    pr->window = pwin;
    pr->path = dupstr(path);

    item_insert((void *) &process_handles, &nprocesses, pi.hProcess);
    nprocesses -= 1;
    item_insert((void *) &process_records, &nprocesses, pr);

    return pwin;
};
예제 #9
0
void StartupRunner::_SpawnProcess(LPTSTR ptzCommandLine, DWORD dwFlags)
{
    ASSERT(!(dwFlags & ERK_WAITFOR_QUIT && dwFlags & ERK_WAITFOR_IDLE));
    
    //
    // The following cases need to be supported:
    //
    // 1. "C:\Program Files\App\App.exe" -params
    // 2. C:\Program Files\App\App.exe -params
    // 3. App.exe -params  (App.exe is in %path% or HKLM->REGSTR_PATH_APPPATHS)
    // and all the above cases without arguments.
    //
    // Note that 'App.exe' may contain spaces too
    //
    // CreateProcess handles 1 and 2, ShellExecuteEx handles 1 and 3.
    // So if the first token doesn't contain path characters (':' or '\')
    // ShellExecuteEx is used. That's really ugly but it *should* work.
    //
    TCHAR tzToken[MAX_LINE_LENGTH] = { 0 };
    LPCTSTR ptzArgs = NULL;
    
    GetToken(ptzCommandLine, tzToken, &ptzArgs, FALSE);
    
    HANDLE hProcess = NULL;
    
    if (strchr(tzToken, _T('\\')) || strchr(tzToken, _T(':')))
    {
        hProcess = _CreateProcess(ptzCommandLine);
    }
    else
    {
        hProcess = _ShellExecuteEx(tzToken, ptzArgs);
    }
    
    if (hProcess != NULL)
    {
        if (dwFlags & ERK_WAITFOR_QUIT)
        {
            WaitForSingleObject(hProcess, INFINITE);
        }
        else if (dwFlags & ERK_WAITFOR_IDLE)
        {
            WaitForInputIdle(hProcess, INFINITE);
        }
        
        CloseHandle(hProcess);
    }
    else
    {
        TRACE("StartupRunner failed to launch '%s'", ptzCommandLine);
    }
}
예제 #10
0
//---------------------------------------------------------------------------
//do inter-key delay
void TPushKeys::DoKeyDelay()
{
	if (Process==NULL)
	{
		//timed delay
		DoDelay(KeyDelayValue);
	}
	else //wait for input buffer to empty from process passed to onpus event
	{
		WaitForInputIdle(Process,ProcessWait);
	}

}
예제 #11
0
파일: lib_task.c 프로젝트: bencz/DotGnu
/*
 * private static bool WaitForInputIdle(IntPtr processHandle,
 *										int processID, int milliseconds);
 */
ILBool _IL_Process_WaitForInputIdle(ILExecThread *_thread,
									ILNativeInt processHandle,
									ILInt32 processID,
									ILInt32 milliseconds)
{
#ifdef IL_WIN32_PLATFORM
	return WaitForInputIdle((HANDLE)processHandle, (DWORD)milliseconds);
#else
	/* "Idle" has no meaning on non-Win32 platforms so just pretend
	   that the process is fully initialized and ready to go */
	return 1;
#endif
}
예제 #12
0
bool CWSWindow::GetWindowFromProcID()
{
	m_hWnd = NULL;
	HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, TRUE, m_dwProcID);
	if (hProc == NULL)
	{
		LOG_WS_ERROR(_T("OpenProcess failed"));
		return false;
	}
	WaitForInputIdle(hProc, INFINITE);
	EnumWindows(&EnumWindowsProc, reinterpret_cast<LPARAM>(this));

	return (m_hWnd != NULL);
}
예제 #13
0
파일: Html.c 프로젝트: shah-/c-projs
static int ExtractLinks()
{
  static WCHAR szNotepad[16];
  PROCESS_INFORMATION pi = {0};
  STARTUPINFO si = {sizeof(STARTUPINFO)};
  lstrcpy(szNotepad, L"Notepad.exe");
  GetStartupInfo(&si);
  if(!CreateProcess(0, szNotepad, 0, 0, 0, 0, 0, 0, &si, &pi))
    return 0;
  WaitForInputIdle(pi.hProcess, INFINITE);
  EnumThreadWindows(pi.dwThreadId, NotepadMainWndFindProc, 0);
  CloseHandle(pi.hThread);
  CloseHandle(pi.hProcess);
  return 0;
}
예제 #14
0
BOOL StartExplorer(DWORD timeout, NS_UNUSED BOOL kill)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    TCHAR shellpath[MAX_PATH];

    OutputDebugString(_T("nsRE::StartExplorer"));

    if (FindWindow(SHELLWND, NULL))
        NS_FAILED(NULL, _T("Explorer already running"));

    GetWindowsDirectory(shellpath, MAX_PATH - 1);
    shellpath[MAX_PATH - 1] = 0;
    _tcsncat(shellpath, SHELL, MAX_PATH - 1);
    shellpath[MAX_PATH - 1] = 0;

    FakeStartupIsDone();

    memset(&pi, 0, sizeof(PROCESS_INFORMATION));
    memset(&si, 0, sizeof(STARTUPINFO));

    si.cb = sizeof(STARTUPINFO);

    if(!CreateProcess(NULL,     /* No module name (use command line) */
        shellpath,              /* Command line */
        NULL,                   /* Process handle not inheritable */
        NULL,                   /* Thread handle not inheritable */
        FALSE,                  /* Set handle inheritance to FALSE */
        0,                      /* No creation flags */
        NULL,                   /* Use parent's environment block */
        NULL,                   /* Use parent's starting directory */
        &si,                    /* Pointer to STARTUPINFO structure */
        &pi))                   /* Pointer to PROCESS_INFORMATION structure */
        NS_FAILED(NULL, _T("Cannot spawn explorer process"));

    switch (WaitForInputIdle(pi.hProcess, timeout))
    {
        case 0            : break; /* OK */
        case WAIT_TIMEOUT :
            if (timeout == IGNORE) break; /* OK as requested */
            NS_FAILED(pi.hProcess, _T("Timeout while waiting for explorer process"));
        case WAIT_FAILED  : NS_FAILED(pi.hProcess, _T("Error while waiting for explorer process"));
        default           : NS_FAILED(pi.hProcess, _T("This should not be reached"));
    }

    return TRUE;
}
예제 #15
0
void InitDbgConsole()
{
	WCHAR CommandLine[200];
	STARTUPINFO siStartInfo;  
  //定义一个用于产生子进程的PROCESS_INFORMATION结构体 (定义见CreateProcess,函数说明)  
    PROCESS_INFORMATION piProcInfo; 

	SECURITY_ATTRIBUTES  sec_att;     
    sec_att.bInheritHandle       = TRUE;     
    sec_att.lpSecurityDescriptor = NULL;     
    sec_att.nLength              = sizeof(SECURITY_ATTRIBUTES);  

	if   (!CreatePipe(&hRead, &hWrite,&sec_att, 0))  
          return;  

	HANDLE hCurrentProcess;
	DuplicateHandle(GetCurrentProcess(),GetCurrentProcess(),GetCurrentProcess(),&hCurrentProcess, 0, TRUE, DUPLICATE_SAME_ACCESS);
	wsprintfW(CommandLine,L"DbgDisplay.exe %d %d",hRead,hCurrentProcess);
	ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );  
	siStartInfo.cb = sizeof(STARTUPINFO);  
	siStartInfo.wShowWindow=TRUE;//此成员设为TRUE的话则显示新建进程的主窗口
	siStartInfo.dwFlags  |= STARTF_USESHOWWINDOW;  
	/*siStartInfo.dwFlags  |= STARTF_USESTDHANDLES;  
	siStartInfo.hStdOutput = 0;     //意思是:子进程的stdout输出到hStdOutWrite  
	siStartInfo.hStdError  =  0;        //意思是:子进程的stderr输出到hStdErrWrite  
	siStartInfo.hStdInput  = hRead;  */
  
	// 产生子进程,具体参数说明见CreateProcess函数  
	int bSuccess = CreateProcess(NULL,  
      CommandLine,    // 子进程的命令行  
      NULL,                   // process security attributes  
      NULL,                   // primary thread security attributes  
      TRUE,                   // handles are inherited  
      CREATE_NEW_CONSOLE,                          // creation flags  
      NULL,                  // use parent's environment  
      NULL,                  // use parent's current directory  
      &siStartInfo,      // STARTUPINFO pointer  
      &piProcInfo);     // receives PROCESS_INFORMATION  
	
   //如果失败,退出  
	if (!bSuccess )
		return;  
	WaitForInputIdle(piProcInfo.hProcess,100);


}
예제 #16
0
bool SteamLaunch(void)
{
	std::string	steamRoot = GetSteamRoot();
	_MESSAGE("steam root = %s", steamRoot.c_str());

	if(steamRoot.empty())
		return false;

	std::string	steamEXEPath = steamRoot + "\\Steam.exe";

	STARTUPINFO			startupInfo = { 0 };
	PROCESS_INFORMATION	procInfo = { 0 };

	startupInfo.cb = sizeof(startupInfo);

	if(!CreateProcess(
		steamEXEPath.c_str(),
		NULL,	// no args
		NULL,	// default process security
		NULL,	// default thread security
		FALSE,	// don't inherit handles
		0,		// no options
		NULL,	// no new environment block
		steamRoot.c_str(),	// new cwd
		&startupInfo, &procInfo))
	{
		PrintLoaderError("Launching Steam failed (%08X).", GetLastError());
		return false;
	}

	// this doesn't do anything useful
	//	bool result = SteamCheckActive();

	// this is an ugly hack. wait for steam to start pumping messages
	WaitForInputIdle(procInfo.hProcess, INFINITE);

	// and then you know some more just because even then it isn't ready
	Sleep(1000 * 5);

	// clean up
	CloseHandle(procInfo.hProcess);
	CloseHandle(procInfo.hThread);

	return true;
}
예제 #17
0
//创建引擎窗体
bool CEngine::CreateEngineInfoBoard()
{
	//为了保持对控制台类型引擎信息显示的原味性,程序创建了另外的一个控制台辅助显示程序,并通过匿名管道向辅助控制台写入引擎信息
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	SECURITY_ATTRIBUTES sa;
	sa.nLength=sizeof(sa);
	sa.lpSecurityDescriptor=NULL;//Default security attributes
	sa.bInheritHandle=true;//handle can be inherited

	if(!CreatePipe(&pde.console_read,&pde.console_write,&sa,BUFSIZE))//创建引擎与显示控制台之间互相通信的匿名管道
	{
		ErrorBox("CreatePipe failed");
		return false;
	}		
	ZeroMemory(&si,sizeof(si));
	si.cb=sizeof(si);
	si.dwFlags=STARTF_USESHOWWINDOW |STARTF_USESTDHANDLES;
	si.wShowWindow=SW_HIDE;
	si.hStdInput=pde.console_read;
	si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	si.hStdError=GetStdHandle(STD_ERROR_HANDLE);
	if(!CreateProcess("bin\\console1.exe",NULL,NULL,NULL,true,0,NULL,gameSet.CurDir,&si,&pi))//打开引擎进程
	{
		ErrorBox("CreateProcess console1 failed");
		return false;
	}
	CloseHandle(pde.console_read);
	pde.hCProcess = pi.hProcess;
	CloseHandle(pi.hThread);
	WaitForInputIdle(pi.hProcess,INFINITE);
	while((pde.console_hwnd=GetProcessMainWnd(pi.dwProcessId))==NULL)
	{//(由于进程创建函数是异步的)子进程刚建立时并不能立刻枚举窗口,需要等待
		Sleep(50);
	}
	//设置窗口标题为引擎路径
	SetWindowText(pde.console_hwnd,path);
	//获取窗口菜单句柄
	HMENU hMenu=GetSystemMenu(pde.console_hwnd,NULL);
	//使关闭按钮无效
	EnableMenuItem(hMenu,SC_CLOSE,MF_GRAYED);
	if(gameSet.swEngine==true)
		ShowWindow(pde.console_hwnd,SW_SHOW);
	return true;
}
예제 #18
0
/*
    Función: GetTypeOfApp
    Descripción: Obtiene el tipo de programa en funcion de la espera en la carga
                 de su interface grafico.
    Parametros: 
        program_name            - Nombre y ruta del programa a checkear
        
    Retorno: 
        _GUI_APP__ 
        _CONS_APP__
        _UNK_APP__ 
*/
int 
GetTypeOfApp( LPTSTR program_name )
{
    STARTUPINFO           startup_info;
    PROCESS_INFORMATION   process_information;
    int                   return_function;
    
    memset( & startup_info, 0, sizeof( STARTUPINFO ) );
    
    return_function = _UNK_APP__;
    
    if 
    ( 
        CreateProcess
        (  
            NULL                                  ,
            program_name                          ,
            NULL                                  ,
            NULL                                  ,
            FALSE                                 ,
            CREATE_SUSPENDED | CREATE_NEW_CONSOLE ,      
            NULL                                  ,
            NULL                                  ,
            & startup_info                        ,
            & process_information
        ) 
        == 
        0 
    )
        ShowGetLastErrorString( "GetTypeOfApp:CreateProcess(program_name)" );
    else
    {
        if ( WaitForInputIdle( process_information.hProcess, 0 ) == WAIT_FAILED)
            return_function = _CONS_APP__;
        else
            return_function = _GUI_APP__;
    }
    
    if ( TerminateProcess( process_information.hProcess, 0) == 0 )
        ShowGetLastErrorString( "GetTypeOfApp:TerminateProcess(program)" );
    
    return return_function;
}
예제 #19
0
bool CProcessLauncher::CreateMyProcess()
{
	if( m_lProcessCount > 0 )
	{
		puts("Process is running." );
		return false;
	}

	bool bOK = false;
	if( m_pi.hProcess == NULL )
	{
		if( ::RunProcess( &m_pi, (char *)GetAppName(), GetAppDirectory(), false, NORMAL_PRIORITY_CLASS ) )
		{
			printf( "Process[%s - %d] created.\n", GetAppName(), m_pi.hProcess );

			DWORD dwResult = WAIT_OBJECT_0;
			if( GetStartWait() )
				dwResult = WaitForSingleObject( GetEvent(), 1000 * 120 );	// 실행 후의 데이타 로딩을 최대 2분 기다린다.
			else
				WaitForInputIdle( m_pi.hProcess, 3000 );		

			bOK = ( dwResult == WAIT_OBJECT_0 );

			printf( "Process[%s - %d] wait result:%d\n", GetAppName(), m_pi.hProcess, dwResult );
		}
	}

	if( bOK )
	{
		InterlockedIncrement( &m_lProcessCount );
		BeginMonitor();
	}
	
	if( m_pPeer )
	{
		BEFORESEND( ar, PACKETTYPE_PROCESS_CREATED2 );
		ar << (BYTE)bOK;
		ar << (DWORD)( bOK ? 0 : GetLastError() );
		SEND( ar, m_pPeer, DPID_SERVERPLAYER );
	}

	return bOK;
}
예제 #20
0
파일: main.c 프로젝트: 340211173/mandingo
void spwanAndHook(char *dlltoinject,opt *options){
	STARTUPINFO         sInfo;
	PROCESS_INFORMATION pInfo;

	printf("[Info] Launching process: %s\n",options->cmdline);
	ZeroMemory(&sInfo, sizeof(sInfo));
	sInfo.cb = sizeof(sInfo);
	ZeroMemory(&pInfo, sizeof(pInfo));

	if (CreateProcess(options->cmdline, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sInfo, &pInfo))
	{
		char cmd[512];
		printf("[info] New pid: %d\n",pInfo.dwProcessId);
		sprintf(cmd,"EXECUTING \"%s\" HOOKING PID %d",options->cmdline,pInfo.dwProcessId);
		logger(options->ini,"injector",cmd,strlen(cmd));
		if(WaitForInputIdle((void*)pInfo.hProcess,1000)==WAIT_FAILED) {
			printf("[info] Wait failed, console app? good luck :p\n");
			injecta(pInfo.dwProcessId,dlltoinject,options);
			Sleep(1000);
		}else{
			injecta(pInfo.dwProcessId,dlltoinject,options);
		}
		if(options->waitKeyPress){
			printf("Press [intro] to resume process..\n");
			getchar();
		}
		ResumeThread((void*)pInfo.hThread);
	    CloseHandle(pInfo.hThread);
	    CloseHandle(pInfo.hProcess);
	}else{
		DWORD dwLastError=GetLastError();
		char lpBuffer[256];
	    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,                 // It´s a system error
	                     NULL,                                      // No string to be formatted needed
	                     dwLastError,                               // Hey Windows: Please explain this error!
	                     MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),  // Do it in the standard language
	                     lpBuffer,              // Put the message here
	                     sizeof(lpBuffer),                     // Number of bytes to store the message
	                     NULL);
		printf("[Error] Code %d - %s",GetLastError(),lpBuffer);
	}
}
예제 #21
0
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// StartExplorerShell
// Try to start Explorer in shell mode
//
bool StartExplorerShell(DWORD dwWaitTimeout)
{
    bool bStarted = false;
    TCHAR szOldShell[MAX_PATH] = { 0 };

    DWORD dwCopied = GetPrivateProfileString(_T("boot"), _T("shell"), NULL,
        szOldShell, COUNTOF(szOldShell), _T("system.ini"));

    // If this user account has limited access rights and
    // the shell is in HKLM, GetPrivateProfileString returns 0
    if (dwCopied > 0 && dwCopied < (COUNTOF(szOldShell)-1))
    {
        if (WritePrivateProfileString(
            _T("boot"), _T("shell"), _T("explorer.exe"), _T("system.ini")))
        {
            // We have successfully set Explorer as shell, now launch it...
            SHELLEXECUTEINFO sei = { 0 };
            sei.cbSize = sizeof(sei);
            sei.fMask = SEE_MASK_DOENVSUBST | SEE_MASK_NOCLOSEPROCESS;
            sei.lpVerb = _T("open");
            sei.lpFile = _T("%windir%\\explorer.exe");

            if (LSShellExecuteEx(&sei))
            {
                // If we don't wait here, there'll be a race condition:
                // We may reset the 'shell' setting before Explorer reads it.
                if (WaitForInputIdle(sei.hProcess, dwWaitTimeout) == 0)
                {
                    bStarted = true;
                }

                CloseHandle(sei.hProcess);
            }

            WritePrivateProfileString(
                _T("boot"), _T("shell"), szOldShell, _T("system.ini"));
        }
    }

    return bStarted;
}
예제 #22
0
static int start_dde_server (LPCTSTR prog)
{
    PROCESS_INFORMATION pi;
    STARTUPINFO si;
    
    ZeroMemory(&si, sizeof si);
    si.cb = sizeof si;
    
    if (!CreateProcess(NULL, (LPTSTR) prog, NULL, NULL, FALSE, 0,
		       NULL, NULL, &si, &pi)) {
	fprintf(stderr, "DDE: couldn't start process %s\n", prog);
	return 1;
    }

    WaitForInputIdle(pi.hProcess, MAX_INPUT_IDLE_WAIT);

    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
    
    return 0;
}
예제 #23
0
파일: sexe.c 프로젝트: buzz26/toyBox
//
//	テスト起動
//	in: exe_name .. プログラムファイルパス
//	    option_name .. プログラムコマンドラインオプション
//	    pattern .. 終了パターン
//
void execute_program(HWND hDlg, TCHAR *exe_name, TCHAR *option_name, int pattern)
{
	PROCESS_INFORMATION pi;
	DWORD count;

	// プログラムを起動する。
	if(execute_process(exe_name, option_name, &pi)) {
		WaitForInputIdle(pi.hProcess,INFINITE);
		SetForegroundWindow(hDlg);
		// プログラムを起動しました。\nOKをクリックするとプログラムを終了します。\n終了しない場合、手動でプログラムを終了させてください。\n\n※これは sexe からプログラムを終了されられるかどうかのテストで、\n 実際にサービスでの正常動作が保証されるわけではありません\n のでご注意ください。
		MessageBoxResourceText(hDlg, IDS_TEST_EXECUTE, NULL, HEADER, MB_OK);
		process_id = pi.dwProcessId;
// 2011/9/19 kimukou.buzz
		if(pattern == END_CTRL_BREAK) {
			GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, process_id);
		}else if(pattern == END_CTRL_C) {
			GenerateConsoleCtrlEvent(CTRL_BREAK_C, process_id);
// 2011/9/19 kimukou.buzz
		} else {
			EnumWindows(EnumWindowsProc, pattern);
		}
		count = GetTickCount() + 30 * 1000;
		// プログラム終了もしくタイムアウト(30s)で抜ける
		while(count > GetTickCount()) {
	    	if(WaitForSingleObject(pi.hProcess, 0) != WAIT_TIMEOUT) {
				break;
			}
			Sleep(100);
		}
		// 2001/11/9
		CloseHandle(pi.hThread);
		CloseHandle(pi.hProcess);
	}
// 2011/9/19 kimukou.buzz
	//if(pattern == END_CTRL_BREAK) {
	if(pattern == END_CTRL_BREAK || pattern == END_CTRL_C) {
// 2011/9/19 kimukou.buzz
		FreeConsole();
	}
}
예제 #24
0
    //-------------------------------------------------------------------------
    Bool Injector::Load( HANDLE process, const CHAR* dll_path )
    {
        xassert(_process == NULL);

        // attempt loop
        for( Index attempt = 0; attempt < LOAD_ATTEMPT_COUNT; ++attempt )
        {
            // wait until ready. this doesnt work in all cases, therefore ignore
            // return value and rely on following code and multiple attempts to 
            // qualify a succcessful injection.
            WaitForInputIdle(process, LOAD_WAIT_DELAY);

            // initialize symbol loader
            if( SymInitialize(process, NULL, FALSE) )
            {
                // save process handle
                _process = process;

                // load initial modules
                if( _LoadSymbolModule("kernel32.dll") )
                {
                    // allocate argument memory
                    _argument_memory = VirtualAllocEx(process, NULL, INJECTOR_ARGUMENT_MEMORY, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);

                    // if allocated
                    if( _argument_memory )
                    {
                        // inject dll
                        if( _InjectDll(dll_path) )
                            return true;
                    }
                }
            }

            // fail
            Unload();
        }

        return false;
    }
예제 #25
0
파일: win.c 프로젝트: IBwWG/systools
int systools_win_create_process( const char *app, const char *args, const char *wd, int hide, int wait ) {
	STARTUPINFO si;
	PROCESS_INFORMATION pi;	
	char *cmdline = malloc(32*1024); 
	char wdir[MAX_PATH];
	DWORD wdir_ok;

	sprintf(cmdline,"\"%s\" %s",app,args? args : "");
	wdir_ok = wd ? GetShortPathName(wd,&wdir,MAX_PATH) : 0;

	memset(&si,0,sizeof(STARTUPINFO));
	memset(&pi,0,sizeof(PROCESS_INFORMATION));
	si.cb = sizeof(STARTUPINFO);
	si.dwX = si.dwY = si.dwXSize = si.dwYSize = CW_USEDEFAULT;
	si.wShowWindow = hide ? SW_HIDE : SW_SHOW;
	si.dwFlags 
		= STARTF_USEPOSITION
		| STARTF_USESIZE
		| STARTF_USESHOWWINDOW
		| STARTF_FORCEONFEEDBACK;

	if (CreateProcess
			( NULL
			, cmdline
			, NULL,NULL,0
			, CREATE_DEFAULT_ERROR_MODE
			, NULL
			, wdir_ok? wdir : NULL
			, &si, &pi)) {
		free(cmdline);
		if (wait) {
			WaitForInputIdle(pi.hProcess,INFINITE);
			WaitForSingleObject(pi.hProcess,INFINITE);		
		}
		return 0;
	}
	free(cmdline);
	return GetLastError();
}
예제 #26
0
BOOL Execute(HWND hwnd, LPCTSTR program, LPCTSTR params)
{
    TCHAR szCmdLine[MAX_PATH];
    lstrcpy(szCmdLine, TEXT("\""));
    lstrcat(szCmdLine, program);
    lstrcat(szCmdLine, TEXT("\" "));
    lstrcat(szCmdLine, params);

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    BOOL b = CreateProcess(NULL, szCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);
    if (b)
    {
        WaitForInputIdle(pi.hProcess, 1500);
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return TRUE;
    }
    return FALSE;
}
예제 #27
0
파일: utils.cpp 프로젝트: KDE/snoretoast
bool startProcess(const std::filesystem::path &app)
{
    STARTUPINFO info = {};
    info.cb = sizeof(info);
    PROCESS_INFORMATION pInfo = {};
    const auto application = app.wstring();
    if (!CreateProcess(const_cast<wchar_t *>(application.c_str()),
                       const_cast<wchar_t *>(application.c_str()), nullptr, nullptr, false,
                       DETACHED_PROCESS | INHERIT_PARENT_AFFINITY | CREATE_NO_WINDOW, nullptr,
                       nullptr, &info, &pInfo)) {
        tLog << L"Failed to start: " << app;
        return false;
    }
    WaitForInputIdle(pInfo.hProcess, INFINITE);
    DWORD status;
    GetExitCodeProcess(pInfo.hProcess, &status);
    CloseHandle(pInfo.hProcess);
    CloseHandle(pInfo.hThread);
    tLog << L"Started: " << app << L" Status: "
         << (status == STILL_ACTIVE ? L"STILL_ACTIVE" : std::to_wstring(status));
    return status == STILL_ACTIVE;
}
예제 #28
0
static void spawn_linphonec(int argc, char *argv[]){
	PROCESS_INFORMATION pinfo;
	STARTUPINFO si;
	ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);
	ZeroMemory( &pinfo, sizeof(pinfo) );


	BOOL ret=CreateProcess(NULL,"linphoned.exe --pipe -c NUL",
		NULL,
		NULL,
		FALSE,
		0,
		NULL,
		NULL,
		&si,
		&pinfo);
	if (!ret){
		fprintf(stderr,"Spawning of linphonec.exe failed.\n");
	}else{
		WaitForInputIdle(pinfo.hProcess,1000);
	}
}
예제 #29
0
파일: Processes.cpp 프로젝트: Bo98/bootil
		BOOTIL_EXPORT void* Start( const Bootil::BString& strName, const Bootil::BString& strParam, bool bShow )
		{
			#ifdef _WIN32
			SHELLEXECUTEINFO shExecInfo;
				shExecInfo.cbSize			= sizeof(SHELLEXECUTEINFO);
				shExecInfo.fMask			= SEE_MASK_FLAG_NO_UI | SEE_MASK_NOCLOSEPROCESS;
				shExecInfo.hwnd				= NULL;
				shExecInfo.lpVerb			= NULL;
				shExecInfo.lpFile			= strName.c_str();
				shExecInfo.lpParameters		= strParam.c_str();
				shExecInfo.lpDirectory		= NULL;
				shExecInfo.nShow			= bShow ? SW_SHOWNORMAL : SW_HIDE;
				shExecInfo.hInstApp			= NULL;

			if ( ShellExecuteEx( &shExecInfo ) )
			{
				WaitForInputIdle( shExecInfo.hProcess, INFINITE );
				return shExecInfo.hProcess;
			}
			#endif

			return NULL;
		}
예제 #30
0
static HANDLE
launch_helper()
{
	HANDLE app = NULL;
	SYSTEM_INFO si;
	DWORD ret;

	GetSystemInfo(&si);


	/* If we are running on a x64 system, hook 32 bit apps as well
	   by launching a 32 bit helper process. */
	if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
		char cmd[] = "seamlessrdphook32.exe";
		app = launch_app(cmd);
		if (!app) {
			char msg[256];
			_snprintf(msg, sizeof(msg),
				"Unable to launch the requested application:\n%s", cmd);
			message(msg);
		}

		/* Wait until helper is started, so that it gets included in
		   the process enum */

		ret = WaitForInputIdle(app, HELPER_TIMEOUT);
		switch (ret) {
		case 0:
			break;
		case WAIT_TIMEOUT:
		case WAIT_FAILED:
			message("Hooking helper failed to start within time limit");
			break;
		}
	}
	return app;
}