Пример #1
0
BOOL
doexec(
    SOCKET  ClientSocket
    )
{
    PSESSION_DATA   Session = CreateSession();
    SECURITY_ATTRIBUTES SecurityAttributes;
    DWORD ThreadId;
    HANDLE HandleArray[3];
	int i;

    SecurityAttributes.nLength = sizeof(SecurityAttributes);
    SecurityAttributes.lpSecurityDescriptor = NULL; // Use default ACL
    SecurityAttributes.bInheritHandle = FALSE; // No inheritance

    //
    // Store the client socket handle in the session structure so the thread
    // can get at it. This also signals that the session is connected.
    //
    Session->ClientSocket = ClientSocket;

    //
    // Create the session threads
    //
    Session->ReadShellThreadHandle = 
        CreateThread(&SecurityAttributes, 0,
                     (LPTHREAD_START_ROUTINE) SessionReadShellThreadFn, 
                     (LPVOID) Session, 0, &ThreadId);

    if (Session->ReadShellThreadHandle == NULL) {
        holler("Failed to create ReadShell session thread, error = %s", 
			itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL);

        //
        // Reset the client pipe handle to indicate this session is disconnected
        //
        Session->ClientSocket = INVALID_SOCKET;
        return(FALSE);
    }

    Session->WriteShellThreadHandle = 
        CreateThread(&SecurityAttributes, 0, 
                     (LPTHREAD_START_ROUTINE) SessionWriteShellThreadFn, 
                     (LPVOID) Session, 0, &ThreadId);

    if (Session->WriteShellThreadHandle == NULL) {
        holler("Failed to create ReadShell session thread, error = %s", 
			itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL);

        //
        // Reset the client pipe handle to indicate this session is disconnected
        //
        Session->ClientSocket = INVALID_SOCKET;

        TerminateThread(Session->WriteShellThreadHandle, 0);
        return(FALSE);
    }

    //
    // Wait for either thread or the shell process to finish
    //

    HandleArray[0] = Session->ReadShellThreadHandle;
    HandleArray[1] = Session->WriteShellThreadHandle;
    HandleArray[2] = Session->ProcessHandle;

	
    i = WaitForMultipleObjects(3, HandleArray, FALSE, 0xffffffff);
    
	
	switch (i) {
      case WAIT_OBJECT_0 + 0:
        TerminateThread(Session->WriteShellThreadHandle, 0);
        TerminateProcess(Session->ProcessHandle, 1);
        break;

      case WAIT_OBJECT_0 + 1:
        TerminateThread(Session->ReadShellThreadHandle, 0);
        TerminateProcess(Session->ProcessHandle, 1);
        break;
      case WAIT_OBJECT_0 + 2:
        TerminateThread(Session->WriteShellThreadHandle, 0);
        TerminateThread(Session->ReadShellThreadHandle, 0);
        break;
 
	  default:
        holler("WaitForMultipleObjects error: %s", 
			itoa(GetLastError(), smbuff, 10), NULL, NULL, NULL, NULL, NULL);

        break;
    }


    // Close my handles to the threads, the shell process, and the shell pipes
	shutdown(Session->ClientSocket, SD_BOTH);
  	closesocket(Session->ClientSocket);
	
	DisconnectNamedPipe(Session->ReadPipeHandle);
    CloseHandle(Session->ReadPipeHandle);

	DisconnectNamedPipe(Session->WritePipeHandle);
    CloseHandle(Session->WritePipeHandle);


    CloseHandle(Session->ReadShellThreadHandle);
    CloseHandle(Session->WriteShellThreadHandle);

    CloseHandle(Session->ProcessHandle);
 
    free(Session);

    return(TRUE);
}
Пример #2
0
CDragDrop::~CDragDrop()
{
	//DestroyDragImageBits();
	//DestroyDragImageWindow();

	if (mb_DragDropRegistered && ghWnd)
	{
		mb_DragDropRegistered = FALSE;
		RevokeDragDrop(ghWnd);
	}

	MSectionLockSimple CS;
	CS.Lock(mp_CrThreads);
	BOOL lbEmpty = m_OpThread.empty() && !InDragDrop();
	CS.Unlock();

	if (!lbEmpty)
	{
		if (MessageBox(ghWnd, L"Not all shell operations was finished!\r\nDo You want to terminate them (it's may be harmful)?",
		              gpConEmu->GetDefaultTitle(), MB_YESNO|MB_ICONEXCLAMATION) == IDYES)
		{
			// Terminate all shell (copying) threads
			CS.Lock(mp_CrThreads);
			//std::vector<ThInfo>::iterator iter = m_OpThread.begin();

			//while (iter != m_OpThread.end())
			while (m_OpThread.size() > 0)
			{
				INT_PTR j = m_OpThread.size()-1;
				const ThInfo* iter = &(m_OpThread[j]);

				HANDLE hThread = iter->hThread;
				TerminateThread(hThread, 100);
				CloseHandle(hThread);

				//iter = m_OpThread.erase(iter);
				m_OpThread.erase(j);
			}

			CS.Unlock();
		}
		else
		{
			// Wait until finished
			BOOL lbActive = TRUE;

			while (lbActive)
			{
				Sleep(100);
				CS.Lock(mp_CrThreads);
				lbActive = (!m_OpThread.empty()) || InDragDrop();
				CS.Unlock();
			}
		}
	}
	else
	{
		// незаконченных нитей нет
		// -- Leave Critical Section(&m_CrThreads); -- 101229 секция уже закрыта
	}

	// Завершение всех нитей драга
	TerminateDrag();


	//if (m_pfpi) free(m_pfpi); m_pfpi=NULL;

	//if (mp_DesktopID) { CoTaskMemFree(mp_DesktopID); mp_DesktopID = NULL; }
	SafeDelete(mp_CrThreads);
}
Пример #3
0
static void stubSPUSafeTearDown(void)
{
#ifdef CHROMIUM_THREADSAFE
    CRmutex *mutex;
#endif

    if (!stub_initialized) return;
    stub_initialized = 0;

#ifdef CHROMIUM_THREADSAFE
    mutex = &stub.mutex;
    crLockMutex(mutex);
#endif
    crDebug("stubSPUSafeTearDown");

#ifdef WINDOWS
# ifndef CR_NEWWINTRACK
    stubUninstallWindowMessageHook();
# endif
#endif

#if defined(CR_NEWWINTRACK)
    crUnlockMutex(mutex);
# if defined(WINDOWS)
    if (RTThreadGetState(stub.hSyncThread)!=RTTHREADSTATE_TERMINATED)
    {
        HANDLE hNative;
        DWORD ec=0;

        hNative = OpenThread(SYNCHRONIZE|THREAD_QUERY_INFORMATION|THREAD_TERMINATE,
                             false, RTThreadGetNative(stub.hSyncThread));
        if (!hNative)
        {
            crWarning("Failed to get handle for sync thread(%#x)", GetLastError());
        }
        else
        {
            crDebug("Got handle %p for thread %#x", hNative, RTThreadGetNative(stub.hSyncThread));
        }

        ASMAtomicWriteBool(&stub.bShutdownSyncThread, true);

        if (PostThreadMessage(RTThreadGetNative(stub.hSyncThread), WM_QUIT, 0, 0))
        {
            RTThreadWait(stub.hSyncThread, 1000, NULL);

            /*Same issue as on linux, RTThreadWait exits before system thread is terminated, which leads
             * to issues as our dll goes to be unloaded.
             *@todo
             *We usually call this function from DllMain which seems to be holding some lock and thus we have to
             * kill thread via TerminateThread.
             */
            if (WaitForSingleObject(hNative, 100)==WAIT_TIMEOUT)
            {
                crDebug("Wait failed, terminating");
                if (!TerminateThread(hNative, 1))
                {
                    crDebug("TerminateThread failed");
                }
            }
            if (GetExitCodeThread(hNative, &ec))
            {
                crDebug("Thread %p exited with ec=%i", hNative, ec);
            }
            else
            {
                crDebug("GetExitCodeThread failed(%#x)", GetLastError());
            }
        }
        else
        {
            crDebug("Sync thread killed before DLL_PROCESS_DETACH");
        }

        if (hNative)
        {
            CloseHandle(hNative);
        }
    }
#else
    if (stub.hSyncThread!=NIL_RTTHREAD)
    {
        ASMAtomicWriteBool(&stub.bShutdownSyncThread, true);
        {
            /*RTThreadWait might return too early, which cause our code being unloaded while RT thread wrapper is still running*/
            int rc = pthread_join(RTThreadGetNative(stub.hSyncThread), NULL);
            if (!rc)
            {
                crDebug("pthread_join failed %i", rc);
            }
        }
    }
#endif
    crLockMutex(mutex);
#endif

#ifndef WINDOWS
    crNetTearDown();
#endif

#ifdef CHROMIUM_THREADSAFE
    crUnlockMutex(mutex);
    crFreeMutex(mutex);
#endif
    crMemset(&stub, 0, sizeof(stub));
}
Пример #4
0
void _tmain(int argc, TCHAR *argv[])
{
	g_hStopEvent = CreateEvent(NULL, FALSE, FALSE, NULL);		// WinBash.h
	/*
	CreateEventW (Unicode)
	Creates or opens a named or unnamed event object.

	HANDLE WINAPI CreateEvent(
		_In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes,
		_In_     BOOL                  bManualReset,
		_In_     BOOL                  bInitialState,
		_In_opt_ LPCTSTR               lpName
	);

	*** !LPSECURITY_ATTRIBUTES

	The SECURITY_ATTRIBUTES structure contains the security descriptor for an object and specifies
	whether the handle retrieved by specifying this structure is inheritable.
	This structure provides security settings for objects created by various functions,
	such as CreateFile, CreatePipe, CreateProcess, RegCreateKeyEx, or RegSaveKeyEx.
	
	typedef struct _SECURITY_ATTRIBUTES {
	  DWORD  nLength;
	  LPVOID lpSecurityDescriptor;
	  BOOL   bInheritHandle;
	} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;

		*** LPVOID
		http://kspil.tistory.com/6
		Microsoft Playform SDK를 설치하고 그 하위 디렉토리에서 WinDef.h 파일을 찾으면
		아래와 같은 치환어들이 모두 정의되어 있습니다.
		
		#define WINAPI __stdcall
		typedef unsigned char BYTE;
		typedef unsigned long * PDWORD;
		typedef void far * LPVOID;

			*** far * http://egloos.zum.com/jhjang/v/2369128
			far 포인터 형 함수는 unix와 ansi c에서는 제공이 되지 않고 도스와 윈도우에서만 사용하였지만
			최근에는 WIN32로 환경이 바뀌면서 사용하지 않게 되었다.
			좀더 상세히 말하면 near포인터와 far포인터는 windef.h파일에 정의되는데 win32로 바뀌면서 빈 문장열로 처리하도록 변경되었다.

		단순히 Microsoft에서 좀 더 이해하기 쉬우면서 짧은 타입명을 제시한 것이다.

		이름에는 일정한 형식이 있다.

		1. 포인터 타입(*)인 경우에는 P로 시작하며 - PINT, PDWORD 등
		2. far 포인터(far *)인 경우에는 L로 시작합니다 - LPVOID 등
		3. unsigned 타입일 경우 U로 시작합니다. - UINT, ULONG 등
		4. BYTE, WORD, DWORD 등은 어셈블리에서 쓰이던 데이터 형식의 이름을 따왔습니다.
	
	*** LPCTSTR
	http://egloos.zum.com/pelican7/v/1768951

	LP는 long pointer를 나타내는 약어로서 16bit시절의 윈도우의 유산이다.
	현재 LP(long pointer)는 .Net에서는 64bit pointer를,
	VC++6.0과 그 이전 버전에서는 32bit pointer를 나타낸다.

	C는 constant, 즉 함수의 내부에서 인자값을 변경하지 말라는 뜻이다. 
	STR은 말그대로 string자료가 될것이라는 뜻으로 내부적으로는 char형 배열에 null값 종료를 의미한다.

	LPSTR = long pointer string = char * 
	LPCTSTR = long pointer constant t_string = const tchar * 

	컴파일러가 precompile option을 보고 환경에 맞게 동작하는 코드를 작성할 수 있는 새로운 변수 모양의 Macro를 선언하게 되었다. 
	그것이 바로 TCHAR, t_char라는 변수다. 
	즉, 자신의 운영체제가 multi-byte환경이면, char형으로, 
	unicode환경이면, w_char, wide char형으로 type casting된다.
	*/

	

	SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
	/*
	SetConsoleCtrlHandler :
	Adds or removes an application-defined HandlerRoutine function
	from the list of handler functions for the calling process.
	If no handler function is specified,
	the function sets an inheritable attribute that determines
	whether the calling process ignores CTRL+C signals.
	
	SetConsoleCtrlHandler(
		__in_opt PHANDLER_ROUTINE HandlerRoutine,
		__in BOOL Add);	

	*** PHANDLER_ROUTINE

	// typedef for ctrl-c handler routines
	typedef
	BOOL
	(WINAPI *PHANDLER_ROUTINE)( __in DWORD CtrlType	);
	*/


	g_hFile = CreateFile(_T("RegFsNotify.txt"), 
		GENERIC_WRITE,				// (0x40000000L)
		FILE_SHARE_READ, 0,			// 0x00000001, 0
		CREATE_ALWAYS, 0, NULL);	// 2, 0, NULL
	/*
	https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
	WINBASEAPI
	__out
	HANDLE
	WINAPI
	CreateFileW(
		__in     LPCWSTR lpFileName,
		__in     DWORD dwDesiredAccess,
					// The requested access to the file or device,
					// which can be summarized as read, write, both or neither zero
		__in     DWORD dwShareMode,
					// The requested sharing mode of the file or device,
					// which can be read, write, both, delete, all of these, or none
		__in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,
					// A pointer to a SECURITY_ATTRIBUTES structure
					// that contains two separate but related data members
					// INULL : the handle returned
					// by CreateFile cannot be inherited by any child processes the application
		__in     DWORD dwCreationDisposition,
		__in     DWORD dwFlagsAndAttributes,
					// The file or device attributes and flags,
					// FILE_ATTRIBUTE_NORMAL being the most common default value for files.
		__in_opt HANDLE hTemplateFile
		);
	*/


	HANDLE hThread[2];

	hThread[0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StartFileMonitor, NULL, 0, NULL);
	hThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)StartRegistryMonitor, NULL, 0, NULL);
	/*
	*** CreateThread
	Creates a thread to execute within the virtual address space of the calling process.
	To create a thread that runs in the virtual address space of another process,
	use the CreateRemoteThread function.

	WINBASEAPI
	__out_opt
	HANDLE
	WINAPI
	CreateThread(
		__in_opt  LPSECURITY_ATTRIBUTES lpThreadAttributes,
						// A pointer to a SECURITY_ATTRIBUTES structure that determines 
						// whether the returned handle can be inherited by child processes.
						// NULL : the handle cannot be inherited.
		__in      SIZE_T dwStackSize,
						// The initial size of the stack, in bytes.
						// 0 : the new thread uses the default size for the executable.
		__in      LPTHREAD_START_ROUTINE lpStartAddress,
		__in_opt __deref __drv_aliasesMem LPVOID lpParameter,
						// A pointer to a variable to be passed to the thread.
		__in      DWORD dwCreationFlags,
						// The flags that control the creation of the thread.
						// 0 : The thread runs immediately after creation.
		__out_opt LPDWORD lpThreadId
						// A pointer to a variable that receives the thread identifier.
						// NULL : the thread identifier is not returned.
		);
	*/


	WaitForMultipleObjects(2, (const HANDLE*)&hThread, TRUE, INFINITE);		// WinBash.h
	/*
	*** WaitForMultipleObjects
	Waits until one or all of the specified objects are
	in the signaled state or the time-out interval elapses.

	WINBASEAPI
	DWORD
	WINAPI
	WaitForMultipleObjects(
		__in DWORD nCount,
		__in_ecount(nCount) CONST HANDLE *lpHandles,
		__in BOOL bWaitAll,
					// TRUE : the function returns when the state of all objects
					// in the lpHandles array is signaled.
		__in DWORD dwMilliseconds
					// The time-out interval, in milliseconds.
					// INFINITE : the function will return only when the specified objects are signaled.
		);
	*/


	TerminateThread(g_hRegWatch[0], 0);
	TerminateThread(g_hRegWatch[1], 0);
	/*
	*** TerminateThread
	WINBASEAPI
	BOOL
	WINAPI
	TerminateThread(
		__in HANDLE hThread,
		__in DWORD dwExitCode
		);

	TerminatedThread를 사용하면 스레드가 제대로 정리되지 않는다.
	대부분 최후의 경우에만 사용해야 하는 위험한 함수다.
	적절하게 종료하기 위한 방법 :
		1. CreateEvent 함수를 사용하여 이벤트 개체를 만든다.
		2. 스레드를 만든다.
		3. 각 스레드는 WaitForSingleObject 함수를 호출하여 이벤트 상태를 모니터링한다.
		4. 각 스레드는 이벤트가 신호를 받는 상태 (WaitForSingleObjtect)가 WAIT_OBJECT_0을 반환)로 설정되었을 때 실행을 종료한다.
	*/


	CloseHandle(g_hStopEvent);
	CloseHandle(g_hFile);
	/*
	WINBASEAPI
	BOOL
	WINAPI
	CloseHandle( __in HANDLE hObject );
	*/

	_tprintf(_T("Program terminating.\n"));
}
Пример #5
0
void ThreadImpl::terminate()
{
    if (m_thread)
        TerminateThread(m_thread, 0);
}
Пример #6
0
WinThread::~WinThread()
{
  TerminateThread(this->_th, 0);
  CloseHandle(this->_th);
  delete this->_call;
}
Пример #7
0
int main(int argc, char *argv[])
{
	CNV11* NV11 = new CNV11(); // Create instance of validator class
	// Start the polling thread, this will not send any polls until
	// the IsPolling variable is true
	HANDLE nv11Thread = StartPollThread(NV11); 
	// Set output to std::cout
	NV11->SetOutputStream(&cout);
	WriteString("Example C++ NV11 SDK\n\nSearching for ports...\n");

	// Find out about the validator and create a connection struct to pass
	// to the validator class
	SSP_COMMAND commandStructure;
	commandStructure.BaudRate = 9600;
	commandStructure.Timeout = 1000;
	commandStructure.RetryLevel = 3;
	commandStructure.IgnoreError = 1;

	char* end;
	// Get port number
	std::vector<string> ports = GetComPorts();
	for (unsigned int i = 0; i < ports.size(); ++i)
		cout << ports[i] << endl;
	string in = "";
	unsigned int portIndex = 0;
	do
	{
		in = GetInputString("Select a port: ");
		portIndex = strtol(in.c_str(), &end, 0);
	} while (portIndex <= 0 || portIndex > ports.size());
	commandStructure.PortNumber = FormatComPort(ports[portIndex-1]); 
		
	// Get ssp address
	int ssp = 0;
	do
	{
		in = GetInputString("SSP Address (Default = 0): ");
		ssp = strtol(in.c_str(), &end, 0);
	} while (ssp < 0 || ssp > 32 || end == in.c_str());
	commandStructure.SSPAddress = (unsigned char)ssp;

	// Get protocol version to use
	int p = 0;
	do
	{
		in = GetInputString("Protocol version: ");
		p = strtol(in.c_str(), &end, 0);
	} while (p <= 0 || p > MAX_PROTOCOL_VERSION);

	// Now connect to validator
	if (NV11->ConnectToValidator(commandStructure, p, 5))
	{
		WriteString("Connected to validator successfully");
		DisplayCommands();
		while  (true)
		{
			// Parse the keys, if this returns false then the user has selected
			// to exit the program
			if (!ParseKeys(NV11))
			{
				IsPolling = false; // Stop polling before exit
				break;
			}

			// If PollFailed is set by the polling thread, attempt to reconnect to the unit
			if (PollFailed)
			{
				// Make 5 attempts to reconnect, if none successful break out
				if (NV11->ConnectToValidator(commandStructure, p, 5)) 
				{
					// If successful reconnect, restart the polling thread and continue
					PollFailed = false;
					TerminateThread(nv11Thread, 0);
					CloseHandle(nv11Thread);
					nv11Thread = StartPollThread(NV11);
				}
				else
					break;
			}
		}
		WriteString("Poll loop stopped");
	}
	TerminateThread(nv11Thread, 0);
	CloseHandle(nv11Thread);
	delete NV11;
	WriteString("Press any key to exit...");
	_getch();
}
VOID
IN_PROCESS_APPLICATION::ShutDownInternal()
{
    DWORD    dwThreadStatus = 0;
    DWORD    dwTimeout = m_pConfig->QueryShutdownTimeLimitInMS();
    HANDLE   handle = NULL;
    WIN32_FIND_DATA fileData;

    if (IsDebuggerPresent())
    {
        dwTimeout = INFINITE;
    }

    if (m_fShutdownCalledFromNative ||
        m_status == APPLICATION_STATUS::STARTING ||
        m_status == APPLICATION_STATUS::FAIL)
    {
        return;
    }

    {
        SRWLockWrapper lock(m_srwLock);

        if (m_fShutdownCalledFromNative ||
            m_status == APPLICATION_STATUS::STARTING ||
            m_status == APPLICATION_STATUS::FAIL)
        {
            return;
        }

        // We need to keep track of when both managed and native initiate shutdown
        // to avoid AVs. If shutdown has already been initiated in managed, we don't want to call into
        // managed. We still need to wait on main exiting no matter what. m_fShutdownCalledFromNative
        // is used for detecting redundant calls and blocking more requests to OnExecuteRequestHandler.
        m_fShutdownCalledFromNative = TRUE;
        m_status = APPLICATION_STATUS::SHUTDOWN;

        if (!m_fShutdownCalledFromManaged)
        {
            // We cannot call into managed if the dll is detaching from the process.
            // Calling into managed code when the dll is detaching is strictly a bad idea,
            // and usually results in an AV saying "The string binding is invalid"
            if (!g_fProcessDetach)
            {
                m_ShutdownHandler(m_ShutdownHandlerContext);
                m_ShutdownHandler = NULL;
            }
        }

        // Release the lock before we wait on the thread to exit.
    }

    if (!m_fShutdownCalledFromManaged)
    {
        if (m_hThread != NULL &&
            GetExitCodeThread(m_hThread, &dwThreadStatus) != 0 &&
            dwThreadStatus == STILL_ACTIVE)
        {
            // wait for graceful shutdown, i.e., the exit of the background thread or timeout
            if (WaitForSingleObject(m_hThread, dwTimeout) != WAIT_OBJECT_0)
            {
                // if the thread is still running, we need kill it first before exit to avoid AV
                if (GetExitCodeThread(m_hThread, &dwThreadStatus) != 0 && dwThreadStatus == STILL_ACTIVE)
                {
                    // Calling back into managed at this point is prone to have AVs
                    // Calling terminate thread here may be our best solution.
                    TerminateThread(m_hThread, STATUS_CONTROL_C_EXIT);
                }
            }
        }
    }

    CloseHandle(m_hThread);
    m_hThread = NULL;
    s_Application = NULL;

    CloseStdErrHandles();

    if (m_pStdFile != NULL)
    {
        fflush(stdout);
        fflush(stderr);
        fclose(m_pStdFile);
    }

    if (m_hLogFileHandle != INVALID_HANDLE_VALUE)
    {
        m_Timer.CancelTimer();
        CloseHandle(m_hLogFileHandle);
        m_hLogFileHandle = INVALID_HANDLE_VALUE;
    }

    // delete empty log file
    handle = FindFirstFile(m_struLogFilePath.QueryStr(), &fileData);
    if (handle != INVALID_HANDLE_VALUE &&
        fileData.nFileSizeHigh == 0 &&
        fileData.nFileSizeLow == 0) // skip check of nFileSizeHigh
    {
        FindClose(handle);
        // no need to check whether the deletion succeeds
        // as nothing can be done
        DeleteFile(m_struLogFilePath.QueryStr());
    }
}
// Will be called by the inprocesshandler
HRESULT
IN_PROCESS_APPLICATION::LoadManagedApplication
(
    VOID
)
{
    HRESULT    hr = S_OK;
    DWORD      dwTimeout;
    DWORD      dwResult;

    ReferenceApplication();

    if (m_status != APPLICATION_STATUS::STARTING)
    {
        // Core CLR has already been loaded.
        // Cannot load more than once even there was a failure
        if (m_status == APPLICATION_STATUS::FAIL)
        {
            hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE;
        }
        else if (m_status == APPLICATION_STATUS::SHUTDOWN)
        {
            hr = HRESULT_FROM_WIN32(ERROR_SHUTDOWN_IS_SCHEDULED);
        }

        goto Finished;
    }

    // Set up stdout redirect
    SetStdOut();

    {
        SRWLockWrapper lock(m_srwLock);
        if (m_status != APPLICATION_STATUS::STARTING)
        {
            if (m_status == APPLICATION_STATUS::FAIL)
            {
                hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE;
            }
            else if (m_status == APPLICATION_STATUS::SHUTDOWN)
            {
                hr = HRESULT_FROM_WIN32(ERROR_SHUTDOWN_IS_SCHEDULED);
            }

            goto Finished;
        }
        m_hThread = CreateThread(
            NULL,       // default security attributes
            0,          // default stack size
            (LPTHREAD_START_ROUTINE)ExecuteAspNetCoreProcess,
            this,       // thread function arguments
            0,          // default creation flags
            NULL);      // receive thread identifier

        if (m_hThread == NULL)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            goto Finished;
        }

        m_pInitalizeEvent = CreateEvent(
            NULL,   // default security attributes
            TRUE,   // manual reset event
            FALSE,  // not set
            NULL);  // name

        if (m_pInitalizeEvent == NULL)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
        }

        // If the debugger is attached, never timeout
        if (IsDebuggerPresent())
        {
            dwTimeout = INFINITE;
        }
        else
        {
            dwTimeout = m_pConfig->QueryStartupTimeLimitInMS();
        }

        const HANDLE pHandles[2]{ m_hThread, m_pInitalizeEvent };

        // Wait on either the thread to complete or the event to be set
        dwResult = WaitForMultipleObjects(2, pHandles, FALSE, dwTimeout);

        // It all timed out
        if (dwResult == WAIT_TIMEOUT)
        {
            // kill the backend thread as loading dotnet timedout
            TerminateThread(m_hThread, 0);
            hr = HRESULT_FROM_WIN32(dwResult);
            goto Finished;
        }
        else if (dwResult == WAIT_FAILED)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            goto Finished;
        }

        // The thread ended it means that something failed
        if (dwResult == WAIT_OBJECT_0)
        {
            hr = E_APPLICATION_ACTIVATION_EXEC_FAILURE;
            goto Finished;
        }

        m_status = APPLICATION_STATUS::RUNNING;
    }
Finished:

    if (FAILED(hr))
    {
        m_status = APPLICATION_STATUS::FAIL;

        UTILITY::LogEventF(g_hEventLog,
            EVENTLOG_ERROR_TYPE,
            ASPNETCORE_EVENT_LOAD_CLR_FALIURE,
            ASPNETCORE_EVENT_LOAD_CLR_FALIURE_MSG,
            m_pConfig->QueryApplicationPath()->QueryStr(),
            m_pConfig->QueryApplicationPhysicalPath()->QueryStr(),
            hr);
    }
    DereferenceApplication();

    return hr;
}
CReg_ControlDlg::~CReg_ControlDlg()
{

	if(hFirstThread!=NULL)
		TerminateThread(hFirstThread, 0);
}
Пример #11
0
int mainproc() {
	memset(&pi, 0, sizeof(pi));

	SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);

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

#ifndef REDIRECTIO
	//Windows does this automatically but since we have a separate app and all, let's make sure.
	si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
	si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
#else
	HANDLE hWriteStdIn, hReadStdOut, hReadStdErr;
	makeOutputPipe(&hWriteStdIn, &si.hStdInput);
	makeInputPipe(&si.hStdOutput, &hReadStdOut);
	makeInputPipe(&si.hStdError, &hReadStdErr);
#endif
	TCHAR* moduleFilename = GetModuleFilenameStr(0);
	TCHAR* appName = replaceFilename(moduleFilename, L"Grabber.exe");
	TCHAR* cmdLine = buildCommandLine(GetCommandLine(), L" -c");

	if (!CreateProcess(appName, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
		ThrowLastOsError(L"Cannot run the core application.");
	CloseHandle(pi.hThread);

	delete cmdLine;
	delete appName;
	delete moduleFilename;

#ifndef REDIRECTIO
	DWORD res = WaitForSingleObject(pi.hProcess, INFINITE);
#else
	//These went to children process
	CloseHandle(si.hStdInput);
	CloseHandle(si.hStdError);
	CloseHandle(si.hStdOutput);

	HANDLE hInputThread = RunTranslationThread(GetStdHandle(STD_INPUT_HANDLE), hWriteStdIn);
#ifdef THREADEDOUTPUT
	HANDLE hOutputThread = RunTranslationThread(hReadStdOut, GetStdHandle(STD_OUTPUT_HANDLE));
	HANDLE hErrorThread = RunTranslationThread(hReadStdErr, GetStdHandle(STD_ERROR_HANDLE));
#else
	HANDLE hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	HANDLE hStdError = GetStdHandle(STD_ERROR_HANDLE);
#endif

	DWORD res = 0;
	do {
#ifndef THREADEDOUTPUT
		TryTranslateOutput(hReadStdOut, hStdOutput);
		TryTranslateOutput(hReadStdErr, hStdError);
#endif
		res = WaitForSingleObject(pi.hProcess, 5);
	} while (res == WAIT_TIMEOUT);


#ifndef THREADEDOUTPUT
	//final part
	TryTranslateOutput(hReadStdOut, hStdOutput);
	TryTranslateOutput(hReadStdErr, hStdError);
#endif

	TerminateThread(hInputThread, -1); //the process ended, no point in even writing there
	CloseHandle(hInputThread);

#ifdef THREADEDOUTPUT
	WaitForSingleObject(hOutputThread, INFINITE); //wait until it reads everything there is
	CloseHandle(hOutputThread);
	WaitForSingleObject(hErrorThread, INFINITE);
	CloseHandle(hErrorThread);
#endif

	CloseHandle(hWriteStdIn);
	CloseHandle(hReadStdErr);
	CloseHandle(hReadStdOut);
#endif

	if (res != WAIT_OBJECT_0)
		ThrowLastOsError(L"Cannot wait on the main process");

	DWORD ExitCode = 0;
	if (!GetExitCodeProcess(pi.hProcess, &ExitCode))
		ThrowLastOsError(L"Cannot retrieve execution result");
	CloseHandle(pi.hProcess);
	return ExitCode;
}
Пример #12
0
void UThread::close()
{
   U_TRACE_NO_PARAM(0, "UThread::close()")

#ifdef _MSWINDOWS_
   DWORD _tid = tid;
#else
   pthread_t _tid = tid; 
#endif

   tid = 0;

   U_INTERNAL_DUMP("tid = %p first = %p next = %p", _tid, first, next)

   U_INTERNAL_ASSERT_POINTER(first)

   UThread* obj;
   UThread** ptr = &first;

   while ((obj = *ptr))
      {
      U_INTERNAL_ASSERT_POINTER(obj)

#  ifdef _MSWINDOWS_
      if (tid == obj->tid)
#  else
      if (pthread_equal(tid, obj->tid))
#  endif
         {
         U_INTERNAL_ASSERT_EQUALS(this, obj)
         U_INTERNAL_ASSERT_EQUALS(next, obj->next)

         *ptr = next;
                next = 0;

         break;
         }

      ptr = &(*ptr)->next;
      }

   if (_tid)
      {
#  ifdef _MSWINDOWS_ // wait for real w32 thread to cleanup
      switch (cancel)
         {
         case cancelImmediate: TerminateThread((HANDLE)_tid, 0); break;

         default: SetEvent(cancellation);
         }

      (void) WaitForSingleObject((HANDLE)_tid, INFINITE);

      (void) U_SYSCALL(CloseHandle, "%p", cancellation);
      (void) U_SYSCALL(CloseHandle, "%p", (HANDLE)_tid);

      _endthreadex(0);
#  else
#   ifdef HAVE_PTHREAD_CANCEL
      (void) U_SYSCALL(pthread_cancel, "%p", _tid);
#   endif

      if (detachstate == PTHREAD_CREATE_JOINABLE) (void) U_SYSCALL(pthread_join, "%p,%p", _tid, 0);
#   ifdef HAVE_PTHREAD_YIELD
      else
         {
         (void) U_SYSCALL_NO_PARAM(pthread_yield);
         }
#   endif
#  endif
      }
}
Пример #13
0
/*
 * Callback for the run_with_progress_bar() function
 */
static LRESULT CALLBACK progress_callback(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	LRESULT loc;
	HANDLE handle;
	static int installation_time = 0;	// active installation time, in secs
	const int msg_max = ARRAYSIZE(progress_message);
	static int msg_index = 0;
	int i;
	// coordinates that we want to disable (=> no resize)
	static LRESULT disabled[9] = { HTLEFT, HTRIGHT, HTTOP, HTBOTTOM, HTSIZE,
		HTTOPLEFT, HTTOPRIGHT, HTBOTTOMLEFT, HTBOTTOMRIGHT };

	switch (message) {

	case WM_CREATE:
		// Reset static variables
		installation_time = 0;
		msg_index = 0;
		hProgress = hDlg;

		// Start modal (disable parent Window)
		EnableWindow(GetParent(hDlg), FALSE);

		init_children(hProgress);
		center_dialog(hProgress);

		// Send a WM_TIMER message every second
		SetTimer(hProgress, 1, 1000, NULL);

		PostMessage(hProgress, UM_PROGRESS_START, 0, 0);

		return (INT_PTR)TRUE;

	case WM_NCHITTEST:
		// Check coordinates to prevent resize actions
		loc = DefWindowProc(hDlg, message, wParam, lParam);
		for(i = 0; i < 9; i++) {
			if (loc == disabled[i]) {
				return (INT_PTR)TRUE;
			}
		}
		return (INT_PTR)FALSE;

	case UM_PROGRESS_START:
		if (progress_thid != -1L) {
			wdi_err("program assertion failed - another operation is in progress");
		} else {
			// Using a thread prevents application freezout on security warning
			progress_thid = _beginthread(progress_thread, 0, NULL);
			if (progress_thid != -1L) {
				return (INT_PTR)TRUE;
			}
			wdi_err("unable to create progress_thread");
		}
		// Fall through and return an error
		wParam = (WPARAM)WDI_ERROR_RESOURCE;

	case UM_PROGRESS_STOP:
		// If you don't re-enable the parent Window before leaving
		// all kind of bad things happen (other Windows get activated, etc.)
		EnableWindow(GetParent(hDlg), TRUE);
		PostQuitMessage((int)wParam);
		DestroyWindow(hProgress);
		return (INT_PTR)TRUE;

	case WM_TIMER:
		if (find_security_prompt() == NULL) {
			installation_time++;	// Only increment outside of security prompts
			if ( (msg_index < msg_max) && (installation_time > 15*(msg_index+1)) ) {
				// Change the progress blurb
				SetWindowTextA(hProgressText, progress_message[msg_index]);
				// Force a full redraw fot the transparent text background
				ShowWindow(hProgressText, SW_HIDE);
				UpdateWindow(hProgressText);
				ShowWindow(hProgressText, SW_SHOW);
				UpdateWindow(hProgressText);
				msg_index++;
			} else if ( (installation_time > 300) && (progress_thid != -1L) ) {
				// Wait 300 (loose) seconds and kill the thread
				// 300 secs is the timeout for driver installation on Vista
				wdi_err("progress timeout expired - KILLING THREAD!");
				handle = OpenThread(THREAD_TERMINATE, FALSE, (DWORD)progress_thid);
				TerminateThread(handle, -1);
				CloseHandle(handle);
				PostQuitMessage(WDI_ERROR_TIMEOUT);
				DestroyWindow(hProgress);
				return (INT_PTR)FALSE;
			}
		}
		return (INT_PTR)TRUE;

	case WM_CLOSE:		// prevent closure using Alt-F4
		return (INT_PTR)TRUE;

	case WM_DESTROY:	// close application
		hProgress = INVALID_HANDLE_VALUE;
		return (INT_PTR)FALSE;

	case WM_CTLCOLORSTATIC:
		pSetBkMode((HDC)wParam, TRANSPARENT);
		return (INT_PTR)pGetStockObject(NULL_BRUSH);
	}
	return DefWindowProc(hDlg, message, wParam, lParam);
}
/// <summary>
/// Process Kinect window menu commands
/// </summary>
/// <param name="commanId">ID of the menu item</param>
/// <param name="param">Parameter passed in along with the commmand ID</param>
/// <param name="previouslyChecked">Check status of menu item before command is issued</param>
void KinectSettings::ProcessMenuCommand(WORD commandId, WORD param, bool previouslyChecked)
{
	DWORD ExitCode;
	FaceTracker* pFaceTracker;
	InbedAPPs* pFallDetect;
	DepthInbedAPPs* pDepthInbedApps;
	LegRaisExcer* pLegRaisExer;
	HandRaisExcer* pHandRaisExer;
	
	m_pKinectWindow->GetFaceTraker(&pFaceTracker);
	m_pPrimaryView->GetFallDetect(&pFallDetect);
	m_pDepthStream->GetDepthInbedAPPs(&pDepthInbedApps);
	m_pPrimaryView->GetLegRaisExcer(&pLegRaisExer);
	m_pPrimaryView->GetHandRaisExcer(&pHandRaisExer);

    if (ID_COLORSTREAM_PAUSE == commandId)
    {
        // Pause color stream
        if (m_pColorStream)
        {
            m_pColorStream->PauseStream(!previouslyChecked);
        }
    }
    else if (ID_COLORSTREAM_RESOLUTION_START <= commandId && ID_COLORSTREAM_RESOLUTION_END >= commandId)
    {
        // Set color stream format and resolution
        if (!m_pColorStream)
        {
            return;
        }

        switch (commandId)
        {
        case ID_RESOLUTION_RGBRESOLUTION640X480FPS30:
            m_pColorStream->SetImageType(NUI_IMAGE_TYPE_COLOR);
            m_pColorStream->SetImageResolution(NUI_IMAGE_RESOLUTION_640x480);
            break;

        case ID_RESOLUTION_RGBRESOLUTION1280X960FPS12:
            m_pColorStream->SetImageType(NUI_IMAGE_TYPE_COLOR);
            m_pColorStream->SetImageResolution(NUI_IMAGE_RESOLUTION_1280x960);
            break;

        case ID_RESOLUTION_YUVRESOLUTION640X480FPS15:
            m_pColorStream->SetImageType(NUI_IMAGE_TYPE_COLOR_YUV);
            m_pColorStream->SetImageResolution(NUI_IMAGE_RESOLUTION_640x480);
            break;

        case ID_RESOLUTION_INFRAREDRESOLUTION640X480FPS30:
            m_pColorStream->SetImageType(NUI_IMAGE_TYPE_COLOR_INFRARED);
            m_pColorStream->SetImageResolution(NUI_IMAGE_RESOLUTION_640x480);
            break;

        case ID_RESOLUTION_RAWBAYERRESOLUTION640X480FPS30:
            m_pColorStream->SetImageType(NUI_IMAGE_TYPE_COLOR_RAW_BAYER);
            m_pColorStream->SetImageResolution(NUI_IMAGE_RESOLUTION_640x480);
            break;

        case ID_RESOLUTION_RAWBAYERRESOLUTION1280X960FPS12:
            m_pColorStream->SetImageType(NUI_IMAGE_TYPE_COLOR_RAW_BAYER);
            m_pColorStream->SetImageResolution(NUI_IMAGE_RESOLUTION_1280x960);
            break;

        default:
            return;
        }

        m_pColorStream->OpenStream();
    }
    else if (ID_DEPTHSTREAM_PAUSE == commandId)
    {
        // Pause depth stream
        if(m_pDepthStream)
        {
            m_pDepthStream->PauseStream(!previouslyChecked);
        }
    }
    else if (ID_DEPTHSTREAM_RANGEMODE_START <= commandId && ID_DEPTHSTREAM_RANGEMODE_END >= commandId)
    {
        // Set depth stream range mode
        bool nearMode = false;
        switch (commandId)
        {
        case ID_RANGEMODE_DEFAULT:
            nearMode = false;
            break;

        case ID_RANGEMODE_NEAR:
            nearMode = true;
            break;

        default:
            return;
        }

        if (m_pDepthStream)
        {
            m_pDepthStream->SetNearMode(nearMode);
        }

        if (m_pSkeletonStream)
        {
            m_pSkeletonStream->SetNearMode(nearMode);
        }
    }
    else if (ID_DEPTHSTREAM_RESOLUTION_START <= commandId && ID_DEPTHSTREAM_RESOLUTION_END >= commandId)
    {
        // Set depth stream resolution
        NUI_IMAGE_RESOLUTION resolution = (NUI_IMAGE_RESOLUTION)(commandId - ID_DEPTHSTREAM_RESOLUTION_START);
        if (m_pDepthStream)
        {
            m_pDepthStream->OpenStream(resolution);
        }
    }
    else if (ID_DEPTHSTREAM_DEPTHTREATMENT_START <= commandId && ID_DEPTHSTREAM_DEPTHTREATMENT_END >= commandId)
    {
        // Set depth stream treatment mode
        DEPTH_TREATMENT treatment = (DEPTH_TREATMENT)(commandId - ID_DEPTHSTREAM_DEPTHTREATMENT_START);
        if (m_pDepthStream)
        {
            m_pDepthStream->SetDepthTreatment(treatment);
        }
    }
    else if (ID_SKELETONSTREAM_PAUSE == commandId)
    {
        // Pause skeleton stream
        if (m_pSkeletonStream)
        {
            m_pSkeletonStream->PauseStream(!previouslyChecked);
        }
    }
    else if (ID_SKELETONSTREAM_TRACKINGMODE_START <= commandId && ID_SKELETONSTREAM_TRACKINGMODE_END >= commandId)
    {
        // Set skeleton track mode
        if (!m_pSkeletonStream)
        {
            return;
        }

        switch (commandId)
        {
        case ID_TRACKINGMODE_DEFAULT:
            m_pSkeletonStream->SetSeatedMode(false);
            break;

        case ID_TRACKINGMODE_SEATED:
            m_pSkeletonStream->SetSeatedMode(true);
            break;

        default:
            return;
        }
    }
    else if (ID_SKELETONSTREAM_CHOOSERMODE_START <= commandId && ID_SKELETONSTREAM_CHOOSERMODE_END >= commandId)
    {
        // Set skeleton chooser mode
        if(!m_pSkeletonStream)
        {
            return;
        }

        m_pSkeletonStream->SetChooserMode(ConvertCommandIdToChooserMode(commandId));
    }
    else
    {
        switch (commandId)
        {
            // Bring up camera color setting dialog
        case ID_CAMERA_COLORSETTINGS:
            m_pColorSettingsView->ShowView();
            break;

            // Bring up camera exposure setting dialog
        case ID_CAMERA_EXPOSURESETTINGS:
            m_pExposureSettingsView->ShowView();
            break;

            // Switch the stream display on primary and secondary stream viewers
        case ID_VIEWS_SWITCH:
            if (m_pColorStream && m_pDepthStream)
            {
                m_pColorStream->SetStreamViewer(m_pDepthStream->SetStreamViewer(m_pColorStream->SetStreamViewer(nullptr)));
            }
            break;

        case ID_FORCE_OFF_IR:
            m_pNuiSensor->NuiSetForceInfraredEmitterOff(param);
            break;

		//////Recording
		case ID_RECORDING_AUDIO:
			if (m_pAudioStream && !m_pAudioStream->GetRecordingStauts())
			{
				m_pAudioStream->SetRecordingStatus(true);
			}
			else if (m_pAudioStream && m_pAudioStream->GetRecordingStauts())
			{
				m_pAudioStream->m_pWaveWriter->Stop();
				delete(m_pAudioStream->m_pWaveWriter);
				m_pAudioStream->m_pWaveWriter=NULL;
				m_pAudioStream->SetRecordingStatus(false);
			}
			break;

		case ID_RECORDING_RGB:
			if (m_pColorStream && !m_pColorStream->GetRecordingStauts())
			{
				m_pColorStream->SetRecordingStatus(true);
			}
			else if (m_pColorStream && m_pColorStream->GetRecordingStauts())
			{
				cvReleaseVideoWriter(&m_pColorStream->m_pwriter);
				m_pColorStream->m_pwriter=nullptr;
				m_pColorStream->SetRecordingStatus(false);
			}
			break;

		case ID_RECORDING_DEPTH:
			if (m_pDepthStream && !m_pDepthStream->GetRecordingStauts())
			{
				m_pDepthStream->SetRecordingStatus(true);
			} 
			else if (m_pDepthStream && m_pDepthStream->GetRecordingStauts())
			{
				cvReleaseVideoWriter(&m_pDepthStream->m_pwriter);
				m_pDepthStream->m_pwriter=nullptr;
				m_pDepthStream->SetRecordingStatus(false);
			}
			break;

		case ID_RECORDING_ALL:
			////RGB
			if (m_pColorStream && !m_pColorStream->GetRecordingStauts())
			{
				m_pColorStream->SetRecordingStatus(true);
			}
			else if (m_pColorStream && m_pColorStream->GetRecordingStauts())
			{
				cvReleaseVideoWriter(&m_pColorStream->m_pwriter);
				m_pColorStream->m_pwriter=nullptr;
				m_pColorStream->SetRecordingStatus(false);
			}
			////Depth
			if (m_pDepthStream && !m_pDepthStream->GetRecordingStauts())
			{
				m_pDepthStream->SetRecordingStatus(true);
			} 
			else if (m_pDepthStream && m_pDepthStream->GetRecordingStauts())
			{
				cvReleaseVideoWriter(&m_pDepthStream->m_pwriter);
				m_pDepthStream->m_pwriter=nullptr;
				m_pDepthStream->SetRecordingStatus(false);
			}
			//////Audio
			if (m_pAudioStream && !m_pAudioStream->GetRecordingStauts())
			{
				m_pAudioStream->SetRecordingStatus(true);
			}
			else if (m_pAudioStream && m_pAudioStream->GetRecordingStauts())
			{
				m_pAudioStream->m_pWaveWriter->Stop();
				delete(m_pAudioStream->m_pWaveWriter);
				m_pAudioStream->m_pWaveWriter=NULL;
				m_pAudioStream->SetRecordingStatus(false);
			}
			break;
		
		////Recording 3D facial model
		case ID_RECORDING_3DFACIALMODEL:
			if (!(pFaceTracker->GetFTRecordingStatus())) 
				pFaceTracker->SetFTRecordingStatus(true);
			else
			{
				pFaceTracker->SetFTRecordingStatus(false);
				pFaceTracker->ResetAUSUcounts();
				pFaceTracker->CloseAUSUfile();
			}
			break;
		////Speech recognition dication pad
		case ID_SPEECHRECOGNITION:
			/*if (!m_threadRun)
			{*/
				//m_hSpeechRecogThread=CreateThread(NULL, 0, m_pKinectWindow->SpeechRecogStaticThread, (PVOID)m_pKinectWindow, 0, 0);
				//m_threadRun=true;
		/*	}
			else
			{*/
				//if (m_hSpeechRecogThread)
				//{
				//	CSimpleDict* pSimpleDict;
				//	m_pKinectWindow->GetSimpleDict(&pSimpleDict);
				//	pSimpleDict->~CSimpleDict();
				//    WaitForSingleObject(m_hSpeechRecogThread, 200);
			 //       CloseHandle(m_hSpeechRecogThread);
				//    m_threadRun=false;
				//}
			//}
			break;

		////In-bed detection
		case ID_FALLDETECTION:
			if (!(pFallDetect->getIsRunFallDetect()))
			{
				pFallDetect->setIsRunFallDetect(TRUE);
				if (!m_FallDetectThreadRun)
				{
				    m_hFallDetectTxt2SpeechThread = CreateThread(NULL, 0, pFallDetect->Txt2SpeechStaticThread, (PVOID)pFallDetect, 0, 0);
			        m_FallDetectThreadRun = TRUE;
				}
			}
			else
			{
				pFallDetect->setIsRunFallDetect(FALSE);
				if (m_FallDetectThreadRun)
				{
					DWORD lpExitCode;
					GetExitCodeThread(m_hFallDetectTxt2SpeechThread, &lpExitCode);
					TerminateThread(m_hFallDetectTxt2SpeechThread, lpExitCode);
					WaitForSingleObject(m_hFallDetectTxt2SpeechThread, 200);
				    CloseHandle(m_hFallDetectTxt2SpeechThread);
				    m_FallDetectThreadRun = FALSE;
				}
			}
			break;

		case ID_MOVEMENTDETECTION:	
			if (!(pFallDetect->getIsRunMovementDetect()))
			{
				pFallDetect->setIsRunMovementDetect(TRUE);
			}
			else
			{
				pFallDetect->setIsRunMovementDetect(FALSE);
			}
			break;

		case ID_OUTOFBEDDETECTION: 		  
			break;

		case ID_LYANGLEDETECTION:
			if (!(pDepthInbedApps->getIsRunLyAngleDetect()))
			{
				pDepthInbedApps->setIsRunLyAngleDetect(TRUE);
			}
			else
			{
				pDepthInbedApps->setIsRunLyAngleDetect(FALSE);
			}
			break;

		case ID_CALLNURSINGBYHANDRAISING:
			if (!(pFallDetect->getIsRunHandsMovementRIC()))
			{
				pFallDetect->setIsRunHandsMovementRIC(TRUE);
				if (!m_NurseCallThreadRun)
				{
				    m_hNurseCallTxt2SpeechThread = CreateThread(NULL, 0, m_pPrimaryView->Txt2SpeechStaticThread, (PVOID)m_pPrimaryView, 0, 0);
			        m_NurseCallThreadRun = TRUE;
				}
				
			}
			else
			{
				pFallDetect->setIsRunHandsMovementRIC(FALSE);
				if (m_NurseCallThreadRun)
				{
					DWORD lpExitCode;
					GetExitCodeThread(m_hNurseCallTxt2SpeechThread, &lpExitCode);
					TerminateThread(m_hNurseCallTxt2SpeechThread, lpExitCode);
					WaitForSingleObject(m_hNurseCallTxt2SpeechThread, 200);
				    CloseHandle(m_hNurseCallTxt2SpeechThread);
				    m_NurseCallThreadRun = FALSE;
				}
			}
			break;

		case ID_VIEWDETECTIONRECS:
			if (!m_processFlag)
			{
				ViewDetectionRes();
			    m_processFlag = TRUE;
			}
			else
			{
				GetViewDetecResProcessStatus(&ExitCode);
				TerminateProcess(m_pi.hProcess, ExitCode);
				m_processFlag = FALSE;
			}
			break;

		case ID_STANDMOVELEGOUTWARD:
			if (!(pLegRaisExer->isRunningExcer()))
			{
				Sleep(5000);
				pLegRaisExer->setRunningExer(TRUE);
				if (!m_LegRaisexcerThreadRun)
				{
				    m_hLegRaisExcerTxt2SpeechThread = CreateThread(NULL, 0, pLegRaisExer->Txt2SpeechStaticThread, (PVOID)pLegRaisExer, 0, 0);
			        m_LegRaisexcerThreadRun = TRUE;
				}
			}
			else
			{
				pLegRaisExer->setRunningExer(FALSE);
				pLegRaisExer->Reset();
				if (m_LegRaisexcerThreadRun)
				{
					DWORD lpExitCode;
					GetExitCodeThread(m_hLegRaisExcerTxt2SpeechThread, &lpExitCode);
					TerminateThread(m_hLegRaisExcerTxt2SpeechThread, lpExitCode);
					WaitForSingleObject(m_hLegRaisExcerTxt2SpeechThread, 200);
				    CloseHandle(m_hLegRaisExcerTxt2SpeechThread);
				    m_LegRaisexcerThreadRun = FALSE;
				}
			}
			break;

		case ID_STANDARMSLIFTWEIGHTS:
			if (!(pHandRaisExer->isRunningExcer()))
			{
				Sleep(5000);
				pHandRaisExer->setRunningExer(TRUE);
				if (!m_HandRaisexcerThreadRun)
				{
				    m_hHandRaisExcerTxt2SpeechThread = CreateThread(NULL, 0, pHandRaisExer->Txt2SpeechStaticThread, (PVOID)pHandRaisExer, 0, 0);
			        m_HandRaisexcerThreadRun = TRUE;
				}
			}
			else
			{
				pHandRaisExer->setRunningExer(FALSE);
				pHandRaisExer->Reset();
				if (m_HandRaisexcerThreadRun)
				{
					DWORD lpExitCode;
					GetExitCodeThread(m_hHandRaisExcerTxt2SpeechThread, &lpExitCode);
					TerminateThread(m_hHandRaisExcerTxt2SpeechThread, lpExitCode);
					WaitForSingleObject(m_hHandRaisExcerTxt2SpeechThread, 200);
				    CloseHandle(m_hHandRaisExcerTxt2SpeechThread);
				    m_HandRaisexcerThreadRun = FALSE;
				}
			}
			break;

        default:
            break;
        }
    }
}
Пример #15
0
static int
ConsoleCloseProc(
    ClientData instanceData,	/* Pointer to ConsoleInfo structure. */
    Tcl_Interp *interp)		/* For error reporting. */
{
    ConsoleInfo *consolePtr = (ConsoleInfo *) instanceData;
    int errorCode;
    ConsoleInfo *infoPtr, **nextPtrPtr;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
    DWORD exitCode;

    errorCode = 0;

    /*
     * Clean up the background thread if necessary. Note that this must be
     * done before we can close the file, since the thread may be blocking
     * trying to read from the console.
     */

    if (consolePtr->readThread) {
	/*
	 * The thread may already have closed on it's own. Check it's exit
	 * code.
	 */

	GetExitCodeThread(consolePtr->readThread, &exitCode);

	if (exitCode == STILL_ACTIVE) {
	    /*
	     * Set the stop event so that if the reader thread is blocked in
	     * ConsoleReaderThread on WaitForMultipleEvents, it will exit
	     * cleanly.
	     */

	    SetEvent(consolePtr->stopReader);

	    /*
	     * Wait at most 20 milliseconds for the reader thread to close.
	     */

	    if (WaitForSingleObject(consolePtr->readThread, 20)
		    == WAIT_TIMEOUT) {
		/*
		 * Forcibly terminate the background thread as a last resort.
		 * Note that we need to guard against terminating the thread
		 * while it is in the middle of Tcl_ThreadAlert because it
		 * won't be able to release the notifier lock.
		 */

		Tcl_MutexLock(&consoleMutex);

		/* BUG: this leaks memory. */
		TerminateThread(consolePtr->readThread, 0);
		Tcl_MutexUnlock(&consoleMutex);
	    }
	}

	CloseHandle(consolePtr->readThread);
	CloseHandle(consolePtr->readable);
	CloseHandle(consolePtr->startReader);
	CloseHandle(consolePtr->stopReader);
	consolePtr->readThread = NULL;
    }
    consolePtr->validMask &= ~TCL_READABLE;

    /*
     * Wait for the writer thread to finish the current buffer, then terminate
     * the thread and close the handles. If the channel is nonblocking, there
     * should be no pending write operations.
     */

    if (consolePtr->writeThread) {
	if (consolePtr->toWrite) {
	    /*
	     * We only need to wait if there is something to write. This may
	     * prevent infinite wait on exit. [python bug 216289]
	     */

	    WaitForSingleObject(consolePtr->writable, INFINITE);
	}

	/*
	 * The thread may already have closed on it's own. Check it's exit
	 * code.
	 */

	GetExitCodeThread(consolePtr->writeThread, &exitCode);

	if (exitCode == STILL_ACTIVE) {
	    /*
	     * Set the stop event so that if the reader thread is blocked in
	     * ConsoleWriterThread on WaitForMultipleEvents, it will exit
	     * cleanly.
	     */

	    SetEvent(consolePtr->stopWriter);

	    /*
	     * Wait at most 20 milliseconds for the writer thread to close.
	     */

	    if (WaitForSingleObject(consolePtr->writeThread, 20)
		    == WAIT_TIMEOUT) {
		/*
		 * Forcibly terminate the background thread as a last resort.
		 * Note that we need to guard against terminating the thread
		 * while it is in the middle of Tcl_ThreadAlert because it
		 * won't be able to release the notifier lock.
		 */

		Tcl_MutexLock(&consoleMutex);

		/* BUG: this leaks memory. */
		TerminateThread(consolePtr->writeThread, 0);
		Tcl_MutexUnlock(&consoleMutex);
	    }
	}

	CloseHandle(consolePtr->writeThread);
	CloseHandle(consolePtr->writable);
	CloseHandle(consolePtr->startWriter);
	CloseHandle(consolePtr->stopWriter);
	consolePtr->writeThread = NULL;
    }
    consolePtr->validMask &= ~TCL_WRITABLE;


    /*
     * Don't close the Win32 handle if the handle is a standard channel during
     * the thread exit process. Otherwise, one thread may kill the stdio of
     * another.
     */

    if (!TclInThreadExit()
	    || ((GetStdHandle(STD_INPUT_HANDLE) != consolePtr->handle)
		&& (GetStdHandle(STD_OUTPUT_HANDLE) != consolePtr->handle)
		&& (GetStdHandle(STD_ERROR_HANDLE) != consolePtr->handle))) {
	if (CloseHandle(consolePtr->handle) == FALSE) {
	    TclWinConvertError(GetLastError());
	    errorCode = errno;
	}
    }

    consolePtr->watchMask &= consolePtr->validMask;

    /*
     * Remove the file from the list of watched files.
     */

    for (nextPtrPtr = &(tsdPtr->firstConsolePtr), infoPtr = *nextPtrPtr;
	    infoPtr != NULL;
	    nextPtrPtr = &infoPtr->nextPtr, infoPtr = *nextPtrPtr) {
	if (infoPtr == (ConsoleInfo *)consolePtr) {
	    *nextPtrPtr = infoPtr->nextPtr;
	    break;
	}
    }
    if (consolePtr->writeBuf != NULL) {
	ckfree(consolePtr->writeBuf);
	consolePtr->writeBuf = 0;
    }
    ckfree((char*) consolePtr);

    return errorCode;
}
VOID CALLBACK xsb_timer_handler(HWND wind, UINT msg, UINT eventid, DWORD time)
{
  if (exitFlag == STILL_WAITING)
    exitFlag = TIMED_OUT; /* tell the timed thread to quit */
  TerminateThread((HANDLE)timedThread, 1);
}
Пример #17
0
// Function name	: RedirectInputThread
// Description	    : 
// Return type		: void 
// Argument         : RedirectInputThreadArg *arg
void RedirectInputThread(RedirectInputThreadArg *arg)
{
	IRemoteShell *pLaunch=NULL;
	HRESULT hr=S_OK;
	HANDLE hObject[2];
	long error=0;
	BSTR berror_msg;
	DWORD ret_val;

	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

	berror_msg = SysAllocString(L"");
	CoGetInterfaceAndReleaseStream (*arg->ppStream, IID_IRemoteShell, (void**) &pLaunch);
	delete arg->ppStream;

	DWORD dwThreadID;
	HANDLE hRSIThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadStdinThread, NULL, 0, &dwThreadID);

	hObject[0] = arg->hEvent;
	hObject[1] = g_hBufferEvent1;

	berror_msg = SysAllocString(L"");
	while (true)
	{
		ret_val = WaitForMultipleObjects(2, hObject, FALSE, INFINITE);
		if (ret_val == WAIT_OBJECT_0+1)
		{
			if (g_num_read > 0)
			{
				SAFEARRAYBOUND bound;
				VARIANT vInput;
				void *pBuf;

				VariantInit(&vInput);
				bound.lLbound = 0;
				bound.cElements = g_num_read;
				vInput.vt = VT_UI1 | VT_ARRAY;
				vInput.parray = SafeArrayCreate(VT_UI1, 1, &bound);

				SafeArrayAccessData(vInput.parray, &pBuf);
				memcpy(pBuf, g_pBuffer, g_num_read);
				SafeArrayUnaccessData(vInput.parray);

				error = 0;
				hr = pLaunch->PutProcessInput(vInput, &error, &berror_msg);
				if (FAILED(hr))
				{
					VariantClear(&vInput);
					printf("PutInteractiveInput failed: %d\n", hr);
					PrintError(hr);
					break;
				}
				if (error)
				{
					VariantClear(&vInput);
					if (wcslen(berror_msg) < 1)
						wprintf(L"PutInteractiveInput failed: %d %s\n", error, berror_msg);
					else
						wprintf(L"PutInteractiveInput failed: %s\n", berror_msg);
					break;
				}
				VariantClear(&vInput);
			}
			ResetEvent(g_hBufferEvent1);
			SetEvent(g_hBufferEvent2);
		}
		else
		{
			//printf("g_hFinishedEvent signalled\n");
		    TerminateThread(hRSIThread, 0);
			break;
		}
	}

	pLaunch->Release();
	CoUninitialize();
}
Пример #18
0
 void THREAD_KILL( THREAD_T *ref ) {
   if (!TerminateThread( *ref, 0 )) FAIL("TerminateThread", GetLastError());
   *ref= NULL;
 }
Пример #19
0
void KillWatcherThread (HWND hDlg)
{
	LuaPerWindowInfo& info = LuaWindowInfo[hDlg];
	TerminateThread(info.fileWatcherThread, 0);
	info.fileWatcherThread = NULL;
}
Пример #20
0
void CShowCalProcess::OnBnClickedButton1()
{
	TerminateThread(handle, 1);
	OnCancel();
	// TODO: 在此添加控件通知处理程序代码
}
Пример #21
0
//force-kill thread
void platform_kill_thread(plat_thread_t* th){
  th->exit = 1;
  TerminateThread(th->tid, 0);
}
Пример #22
0
void folder_watcher::force_stop()
{
	runs_ = false;
	TerminateThread(thread_, 0);
}
Пример #23
0
// Internal API functions
static int wince_init(struct libusb_context *ctx)
{
	int i, r = LIBUSB_ERROR_OTHER;
	HANDLE semaphore;
	TCHAR sem_name[11+1+8]; // strlen(libusb_init)+'\0'+(32-bit hex PID)

	_stprintf(sem_name, _T("libusb_init%08X"), (unsigned int)GetCurrentProcessId()&0xFFFFFFFF);
	semaphore = CreateSemaphore(NULL, 1, 1, sem_name);
	if (semaphore == NULL) {
		usbi_err(ctx, "could not create semaphore: %s", windows_error_str(0));
		return LIBUSB_ERROR_NO_MEM;
	}

	// A successful wait brings our semaphore count to 0 (unsignaled)
	// => any concurent wait stalls until the semaphore's release
	if (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) {
		usbi_err(ctx, "failure to access semaphore: %s", windows_error_str(0));
		CloseHandle(semaphore);
		return LIBUSB_ERROR_NO_MEM;
	}

	// NB: concurrent usage supposes that init calls are equally balanced with
	// exit calls. If init is called more than exit, we will not exit properly
	if ( ++concurrent_usage == 0 ) {	// First init?
		// Initialize pollable file descriptors
		init_polling();

		// Load DLL imports
		if (init_dllimports() != LIBUSB_SUCCESS) {
			usbi_err(ctx, "could not resolve DLL functions");
			r = LIBUSB_ERROR_NOT_SUPPORTED;
			goto init_exit;
		}

		// try to open a handle to the driver
		driver_handle = UkwOpenDriver();
		if (driver_handle == INVALID_HANDLE_VALUE) {
			usbi_err(ctx, "could not connect to driver");
			r = LIBUSB_ERROR_NOT_SUPPORTED;
			goto init_exit;
		}

		// Windows CE doesn't have a way of specifying thread affinity, so this code
		// just has  to hope QueryPerformanceCounter doesn't report different values when
		// running on different cores.
		r = LIBUSB_ERROR_NO_MEM;
		for (i = 0; i < 2; i++) {
			timer_request[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
			if (timer_request[i] == NULL) {
				usbi_err(ctx, "could not create timer request event %d - aborting", i);
				goto init_exit;
			}
		}
		timer_response = CreateSemaphore(NULL, 0, MAX_TIMER_SEMAPHORES, NULL);
		if (timer_response == NULL) {
			usbi_err(ctx, "could not create timer response semaphore - aborting");
			goto init_exit;
		}
		timer_mutex = CreateMutex(NULL, FALSE, NULL);
		if (timer_mutex == NULL) {
			usbi_err(ctx, "could not create timer mutex - aborting");
			goto init_exit;
		}
		timer_thread = CreateThread(NULL, 0, wince_clock_gettime_threaded, NULL, 0, NULL);
		if (timer_thread == NULL) {
			usbi_err(ctx, "Unable to create timer thread - aborting");
			goto init_exit;
		}

		// Wait for timer thread to init before continuing.
		if (WaitForSingleObject(timer_response, INFINITE) != WAIT_OBJECT_0) {
			usbi_err(ctx, "Failed to wait for timer thread to become ready - aborting");
			goto init_exit;
		}
	}
	// At this stage, either we went through full init successfully, or didn't need to
	r = LIBUSB_SUCCESS;

init_exit: // Holds semaphore here.
	if (!concurrent_usage && r != LIBUSB_SUCCESS) { // First init failed?
		if (driver_handle != INVALID_HANDLE_VALUE) {
			UkwCloseDriver(driver_handle);
			driver_handle = INVALID_HANDLE_VALUE;
		}
		if (timer_thread) {
			SetEvent(timer_request[1]); // actually the signal to quit the thread.
			if (WAIT_OBJECT_0 != WaitForSingleObject(timer_thread, INFINITE)) {
				usbi_warn(ctx, "could not wait for timer thread to quit");
				TerminateThread(timer_thread, 1); // shouldn't happen, but we're destroying
												  // all objects it might have held anyway.
			}
			CloseHandle(timer_thread);
			timer_thread = NULL;
		}
		for (i = 0; i < 2; i++) {
			if (timer_request[i]) {
				CloseHandle(timer_request[i]);
				timer_request[i] = NULL;
			}
		}
		if (timer_response) {
			CloseHandle(timer_response);
			timer_response = NULL;
		}
		if (timer_mutex) {
			CloseHandle(timer_mutex);
			timer_mutex = NULL;
		}
	}

	if (r != LIBUSB_SUCCESS)
		--concurrent_usage; // Not expected to call libusb_exit if we failed.

	ReleaseSemaphore(semaphore, 1, NULL);	// increase count back to 1
	CloseHandle(semaphore);
	return r;
}
Пример #24
0
/// <summary>
/// Terminate thread
/// </summary>
/// <param name="code">Exit code</param>
/// <returns>true on success</returns>
bool Thread::Terminate( DWORD code /*= 0*/ )
{
    return (TerminateThread( _handle, code ) == TRUE);
}
Пример #25
0
Файл: Main.cpp Проект: pouba/os
int main()
{
	srand((int)time(NULL));

	node* root_dir = node_create("Computer", NULL, 1);
	node* root = node_create("C:", root_dir, 1);
	node* n1 = node_create("n1", root, 0);
	node* n2 = node_create("n2", root, 0);
	node* n3 = node_create("n3", root, 0);
	node* n4 = node_create("n4", root, 1);
	node* n5 = node_create("n5", root, 1);
	node* n5a = node_create("n5a", n5, 0);
	node* n5b = node_create("n5b", n5, 0);

	char* str = "n1 - aaaaaa\nbbbb\ncccc\nfskdhjs\ndsfj\niuyffj\n\n\nejrwehjr\n";
	n1->content = (char*)malloc(sizeof(char) * strlen(str)+1);
	memcpy(n1->content, str, strlen(str)+1);
	n1->content_len = strlen(n1->content);

	str = "";
	n2->content = (char*)malloc(sizeof(char) * strlen(str)+1);
	memcpy(n2->content, str, strlen(str)+1);
	n2->content_len = strlen(n2->content);

	str = "n3 - ,m,mkjhseur\nsjagfjhsdhj\n";
	n3->content = (char*)malloc(sizeof(char) * strlen(str)+1);
	memcpy(n3->content, str, strlen(str)+1);
	n3->content_len = strlen(n3->content);

	str = "n4 - yighjgjhgfyufyt\n";
	n4->content = (char*)malloc(sizeof(char) * strlen(str)+1);
	memcpy(n4->content, str, strlen(str) + 1);
	n4->content_len = strlen(n4->content);



	str = "n5a - 45455\n";
	n5a->content = (char*)malloc(sizeof(char) * strlen(str)+1);
	memcpy(n5a->content, str, strlen(str) + 1);
	n5a->content_len = strlen(n5a->content);

	str = "n5b - 1010\n";
	n5b->content = (char*)malloc(sizeof(char) * strlen(str)+1);
	memcpy(n5b->content, str, strlen(str) + 1);
	n5b->content_len = strlen(n5b->content);


	pipe_in* in_in = (pipe_in *)malloc(sizeof(pipe_in));
	pipe_out* in_out = (pipe_out *)malloc(sizeof(pipe_out));
	pipe_create(in_in, in_out, 0, 0, 1);

	pipe_in* out_in = (pipe_in *)malloc(sizeof(pipe_in));
	pipe_out* out_out = (pipe_out *)malloc(sizeof(pipe_out));
	pipe_create(out_in, out_out, 0, 0);

	pipe_in* err_in = (pipe_in *)malloc(sizeof(pipe_in));
	pipe_out* err_out = (pipe_out *)malloc(sizeof(pipe_out));
	pipe_create(err_in, err_out, 0, 0);


	HANDLE h_in = std_reader_run(in_in);
	HANDLE h_out = std_writter_run(out_out);
	HANDLE h_err = std_writter_run(err_out);

	run_params par;
	par.cmd_name = "cmd\0";
	par.in = in_out;
	par.out = out_in;
	par.err = err_in;
	par.start_node = root;
	par.root_node = root;
	par.args = (char**)malloc(sizeof(char*) * 1);
	par.args[0] = "-main";
	par.argc = 1;
	par.secret_params = 1;

	c_run( (LPTHREAD_START_ROUTINE) c_cmd_run, &par, 0);

	WaitForSingleObject(h_out, INFINITE);
	WaitForSingleObject(h_err, INFINITE);
	TerminateThread(h_in, 0); // needs to be terminated, otherwise would wait for input forever

	free(par.args);

    return 0;
}
Пример #26
0
RandomWalk::~RandomWalk(){
	TerminateThread(hCollectData, 0);
	TerminateThread(hProccessData, 0);
}
Пример #27
0
/*
 * Curl_wait_for_resolv() waits for a resolve to finish. This function should
 * be avoided since using this risk getting the multi interface to "hang".
 *
 * If 'entry' is non-NULL, make it point to the resolved dns entry
 *
 * This is the version for resolves-in-a-thread.
 */
CURLcode Curl_wait_for_resolv(struct connectdata *conn,
                              struct Curl_dns_entry **entry)
{
  struct thread_data   *td = (struct thread_data*) conn->async.os_specific;
  struct SessionHandle *data = conn->data;
  long   timeout;
  DWORD  status, ticks;
  CURLcode rc;

  DEBUGASSERT(conn && td);

  /* now, see if there's a connect timeout or a regular timeout to
     use instead of the default one */
  timeout =
    conn->data->set.connecttimeout ? conn->data->set.connecttimeout :
    conn->data->set.timeout ? conn->data->set.timeout :
    CURL_TIMEOUT_RESOLVE; /* default name resolve timeout */
  ticks = GetTickCount();

  /* wait for the thread to resolve the name */
  status = WaitForSingleObject(td->event_resolved, timeout);

  /* mark that we are now done waiting */
  ReleaseMutex(td->mutex_waiting);

  /* close our handle to the mutex, no point in hanging on to it */
  CloseHandle(td->mutex_waiting);
  td->mutex_waiting = NULL;

  /* close the event handle, it's useless now */
  CloseHandle(td->event_resolved);
  td->event_resolved = NULL;

  /* has the resolver thread succeeded in resolving our query ? */
  if (status == WAIT_OBJECT_0) {
    /* wait for the thread to exit, it's in the callback sequence */
    if (WaitForSingleObject(td->thread_hnd, 5000) == WAIT_TIMEOUT) {
      TerminateThread(td->thread_hnd, 0);
      conn->async.done = TRUE;
      td->thread_status = (DWORD)-1;
      TRACE(("%s() thread stuck?!, ", THREAD_NAME));
    }
    else {
      /* Thread finished before timeout; propagate Winsock error to this
       * thread.  'conn->async.done = TRUE' is set in
       * Curl_addrinfo4/6_callback().
       */
      SET_SOCKERRNO(conn->async.status);
      GetExitCodeThread(td->thread_hnd, &td->thread_status);
      TRACE(("%s() status %lu, thread retval %lu, ",
             THREAD_NAME, status, td->thread_status));
    }
  }
  else {
    conn->async.done = TRUE;
    td->thread_status = (DWORD)-1;
    TRACE(("%s() timeout, ", THREAD_NAME));
  }

  TRACE(("elapsed %lu ms\n", GetTickCount()-ticks));

  if(entry)
    *entry = conn->async.dns;

  rc = CURLE_OK;

  if (!conn->async.dns) {
    /* a name was not resolved */
    if (td->thread_status == CURLE_OUT_OF_MEMORY) {
      rc = CURLE_OUT_OF_MEMORY;
      failf(data, "Could not resolve host: %s", curl_easy_strerror(rc));
    }
    else if(conn->async.done) {
      if(conn->bits.httpproxy) {
        failf(data, "Could not resolve proxy: %s; %s",
              conn->proxy.dispname, Curl_strerror(conn, conn->async.status));
        rc = CURLE_COULDNT_RESOLVE_PROXY;
      }
      else {
        failf(data, "Could not resolve host: %s; %s",
              conn->host.name, Curl_strerror(conn, conn->async.status));
        rc = CURLE_COULDNT_RESOLVE_HOST;
      }
    }
    else if (td->thread_status == (DWORD)-1 || conn->async.status == NO_DATA) {
      failf(data, "Resolving host timed out: %s", conn->host.name);
      rc = CURLE_OPERATION_TIMEDOUT;
    }
    else
      rc = CURLE_OPERATION_TIMEDOUT;
  }

  Curl_destroy_thread_data(&conn->async);

  if(!conn->async.dns)
    conn->bits.close = TRUE;

  return (rc);
}
Пример #28
0
RTR3DECL(int)     RTTimerDestroy(PRTTIMER pTimer)
{
    /* NULL is ok. */
    if (!pTimer)
        return VINF_SUCCESS;

    /*
     * Validate handle first.
     */
    int rc;
    if (    VALID_PTR(pTimer)
        &&  pTimer->u32Magic == RTTIMER_MAGIC)
    {
#ifdef USE_WINMM
        /*
         * Kill the timer and exit.
         */
        rc = timeKillEvent(pTimer->TimerId);
        AssertMsg(rc == TIMERR_NOERROR, ("timeKillEvent -> %d\n", rc));
        ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
        RTThreadSleep(1);

#else /* !USE_WINMM */

        /*
         * Signal that we want the thread to exit.
         */
        ASMAtomicXchgU32(&pTimer->u32Magic, RTTIMER_MAGIC + 1);
#ifdef USE_APC
        SetEvent(pTimer->hevWait);
        CloseHandle(pTimer->hevWait);
        rc = CancelWaitableTimer(pTimer->hTimer);
        AssertMsg(rc, ("CancelWaitableTimer lasterr=%d\n", GetLastError()));
#else
        LARGE_INTEGER ll = {0};
        ll.LowPart = 100;
        rc = SetWaitableTimer(pTimer->hTimer, &ll, 0, NULL, NULL, FALSE);
        AssertMsg(rc, ("CancelWaitableTimer lasterr=%d\n", GetLastError()));
#endif

        /*
         * Wait for the thread to exit.
         * And if it don't wanna exit, we'll get kill it.
         */
        rc = RTThreadWait(pTimer->Thread, 1000, NULL);
        if (RT_FAILURE(rc))
            TerminateThread((HANDLE)RTThreadGetNative(pTimer->Thread), UINT32_MAX);

        /*
         * Free resource.
         */
        rc = CloseHandle(pTimer->hTimer);
        AssertMsg(rc, ("CloseHandle lasterr=%d\n", GetLastError()));

#endif /* !USE_WINMM */
        RTMemFree(pTimer);
        return rc;
    }

    rc = VERR_INVALID_HANDLE;
    AssertMsgFailed(("Failed to destroy timer %p. rc=%d\n", pTimer, rc));
    return rc;
}
Пример #29
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int gap = bevelWidth + borderWidth;

	switch (message)
	{
		case WM_PAINT:
		{
			OnPaint(hwnd);
		}
		break;

		// ==========

		case BB_RECONFIGURE:
		{
			if (myMenu){ DelMenu(myMenu); myMenu = NULL;}
			GetStyleSettings();
			InvalidateRect(hwndPlugin, NULL, true);
		}
		break;

		// for bbStylemaker
		case BB_REDRAWGUI:
		{
			GetStyleSettings();
			InvalidateRect(hwndPlugin, NULL, true);
		}
		break;

		case WM_DISPLAYCHANGE:
		{
			if(!inSlit)
			{
				// IntelliMove(tm)... <g>
				// (c) 2003 qwilk
				//should make this a function so it can be used on startup in case resolution changed since
				//the last time blackbox was used.
				int relx, rely;
				int oldscreenwidth = ScreenWidth;
				int oldscreenheight = ScreenHeight;
				ScreenWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
				ScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
				if (xpos > oldscreenwidth / 2)
				{
					relx = oldscreenwidth - xpos;
					xpos = ScreenWidth - relx;
				}
				if (ypos > oldscreenheight / 2)
				{
					rely = oldscreenheight - ypos;
					ypos = ScreenHeight - rely;
				}
				MoveWindow(hwndPlugin, xpos, ypos, width, height, true);
			}
		}
		break;

		// ==========

		case BB_BROADCAST:
		{
			szTemp = (char*)lParam;

			if (!_stricmp(szTemp, "@BBShowPlugins") &&  pluginToggle && !inSlit)
			{
				// Show window and force update...
				ShowWindow( hwndPlugin, SW_SHOW);
				InvalidateRect( hwndPlugin, NULL, true);
			}
			else if (!_stricmp(szTemp, "@BBHidePlugins") && pluginToggle && !inSlit)
			{
				// Hide window...
				ShowWindow( hwndPlugin, SW_HIDE);
			}

			//===================

			if (strnicmp(szTemp, "@BBSeekbar", 10))
				return 0;
			szTemp += 10;

			if (!_stricmp(szTemp, "About"))
			{
				char tmp_str[MAX_LINE_LENGTH];
				SendMessage(hwndBlackbox, BB_HIDEMENU, 0, 0);
				sprintf(tmp_str, "%s", szVersion);
				MessageBox(hwndBlackbox, tmp_str, szAppName, MB_OK | MB_TOPMOST);
			}

			//===================

			else if (!_strnicmp(szTemp, "StyleType", 9))
			{
				styleType = atoi(szTemp + 10);
				GetStyleSettings();
				InvalidateRect(hwndPlugin, NULL, true);
			}
			else if (!_strnicmp(szTemp, "TrackStyle", 10))
			{
				trackStyleType = atoi(szTemp + 11);
				GetStyleSettings();
				InvalidateRect(hwndPlugin, NULL, true);
			}
			else if (!_strnicmp(szTemp, "KnobStyle", 9))
			{
				knobStyleType = atoi(szTemp + 10);
				GetStyleSettings();
				InvalidateRect(hwndPlugin, NULL, true);
			}

			else if (!_strnicmp(szTemp, "Appearance", 10))
			{
				appearance = atoi(szTemp + 11);
				track_needsupdate = true;
				knob_needsupdate = true;
				InvalidateRect(hwndPlugin, NULL, true);
				ShowMyMenu(false);
			}
			else if (!_strnicmp(szTemp, "PlayerType", 10))
			{
				playerType = atoi(szTemp + 11);

				// Stop the monitor...
				unsigned long exitcode;
				GetExitCodeThread(hThread_Time, &exitcode);
				TerminateThread(hThread_Time, exitcode);

				FreeLibrary(controlPlugin);
				if(!loadPlayerControl(hInstance, playerType)){
					MessageBox(hwndBlackbox, "Player control plugin not found", szAppName, MB_OK | MB_ICONERROR | MB_TOPMOST);
				}

				// Start the monitoring threads...
				hThread_Time = CreateThread(NULL, 0, TimeProc, NULL, 0, &dwThreadId_Time);

				knob_needsupdate = true;
				InvalidateRect(hwndPlugin, NULL, true);
				ShowMyMenu(false);
			}

			//===================

			else if (!_strnicmp(szTemp, "WidthSize", 9))
			{
				newWidth = atoi(szTemp + 10);
				if(ResizeMyWindow(newWidth, height)){
					track_needsupdate = true;
					knob_needsupdate = true;
					InvalidateRect(hwndPlugin, NULL, true);
				}
			}
			else if (!_strnicmp(szTemp, "HeightSize", 10))
			{
				newHeight = atoi(szTemp + 11);
				if(ResizeMyWindow(width, newHeight)){
					track_needsupdate = true;
					knob_needsupdate = true;
					InvalidateRect(hwndPlugin, NULL, true);
				}
			}

			//===================

			else if (!_stricmp(szTemp, "pluginToggle"))
			{
				pluginToggle = (pluginToggle ? false : true);
				SetWindowModes();
			}
			else if (!_stricmp(szTemp, "OnTop"))
			{
				alwaysOnTop = (alwaysOnTop ? false : true);
				if(!inSlit)SetWindowPos( hwndPlugin,
                                                         alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
                                                         0, 0, 0, 0,
                                                         SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOMOVE);

				ShowMyMenu(false);
			}

			else if (!_stricmp(szTemp, "InSlit"))
			{
				if(inSlit && hSlit){
					// We are in the slit, so lets unload and get out..
					SendMessage(hSlit, SLIT_REMOVE, NULL, (LPARAM)hwndPlugin);

					// Here you can move to where ever you want ;)
					SetWindowPos(hwndPlugin, NULL, xpos, ypos, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
					inSlit = false;
					SetWindowModes();
				}
				/* Make sure before you try and load into the slit that you have
				* the HWND of the slit ;)
				*/
				else if(hSlit){
					// (Back) into the slit..
					inSlit = true;
					SetWindowModes();
					SendMessage(hSlit, SLIT_ADD, NULL, (LPARAM)hwndPlugin);
				}
			}

			else if (!_stricmp(szTemp, "Transparent"))
			{
				transparency = (transparency ? false : true);
				SetWindowModes();
			}
			else if (!_strnicmp(szTemp, "AlphaValue", 10))
			{
				alpha = atoi(szTemp + 11);
				SetWindowModes();
			}
			else if (!_stricmp(szTemp, "SnapToEdge"))
			{
				snapWindow = (snapWindow ? false : true);
				ShowMyMenu(false);
			}
			else if (!_stricmp(szTemp, "ShowBorder"))
			{
				showBorder = (showBorder ? false : true);
				InvalidateRect(hwndPlugin, NULL, false);
				ShowMyMenu(false);
			}
			else if (!_stricmp(szTemp, "AllowTip"))
			{
				allowtip = (allowtip ? false : true);
				SetAllowTip(allowtip);
				ShowMyMenu(false);
			}

			else if (!_stricmp(szTemp, "Vertical"))
			{
				vertical = (vertical ? false : true);
				if(ResizeMyWindow(height, width)){
					track_needsupdate = true;
					knob_needsupdate = true;
					InvalidateRect(hwndPlugin, NULL, true);
				}
				ShowMyMenu(false);
			}
			else if (!_stricmp(szTemp, "Reversed"))
			{
				reversed = (reversed ? false : true);
				track_needsupdate = true;
				knob_needsupdate = true;
				InvalidateRect(hwndPlugin, NULL, true);
				ShowMyMenu(false);
			}

			//===================

			else if (!_stricmp(szTemp, "EditRC"))
			{
				BBExecute(GetDesktopWindow(), NULL,
				ReadString(extensionsrcPath(), "blackbox.editor:", "notepad.exe"),
                                          rcpath, NULL, SW_SHOWNORMAL, false);
			}
			else if (!_stricmp(szTemp, "ReloadSettings"))
			{
				ReadRCSettings();
				GetStyleSettings();

				if(inSlit && hSlit)
				{
					SetWindowModes();
					SendMessage(hSlit, SLIT_UPDATE, NULL, NULL);
				}
				else if(!inSlit || !hSlit)
					SendMessage(hSlit, SLIT_REMOVE, NULL, (LPARAM)hwndPlugin);

				else inSlit = false;
			}
			else if (!_stricmp(szTemp, "SaveSettings"))
			{
				WriteRCSettings();
			}
		}
		break;

		// ==========

		case WM_WINDOWPOSCHANGING:
		{
			// Is SnapWindowToEdge enabled?
			if (!inSlit && snapWindow)
			{
				// Snap window to screen edges (if the last bool is false it uses the current DesktopArea)
				if(IsWindowVisible(hwnd)) SnapWindowToEdge((WINDOWPOS*)lParam, 10, true);
			}
		}
		break;

		// ==========

		case WM_WINDOWPOSCHANGED:
		{
			if(!inSlit)
			{
				WINDOWPOS* windowpos = (WINDOWPOS*)lParam;
				if (0 == (windowpos->flags & SWP_NOMOVE))
				{
					xpos = windowpos->x;
					ypos = windowpos->y;
				}

				if(ResizeMyWindow(windowpos->cx, windowpos->cy) && 0 == (windowpos->flags & SWP_NOSIZE))
				{
					track_needsupdate = true;
					knob_needsupdate = true;
					InvalidateRect(hwndPlugin, NULL, true);
				}
			}
		}
		break;

		// ==========

		case WM_NCHITTEST:
		{
			if (!inSlit && GetKeyState(VK_MENU) & 0xF0)
			{
				return HTBOTTOMRIGHT;
			}
			else
			if (!inSlit && GetKeyState(VK_CONTROL) & 0xF0)
			{
				return HTCAPTION;
			}
		}
		return HTCLIENT;

		// ==========

		case WM_LBUTTONDOWN:
			SetFocus(hwnd);
			SetCapture(hwnd);

			InvalidateRect(hwndPlugin, NULL, false);
			dragging = true;
			SliderOnValueChange(lParam);
			break;
	
		case WM_MOUSEMOVE:
			if (!dragging) break;
			InvalidateRect(hwndPlugin, NULL, false);
			SliderOnValueChange(lParam);
			break;

		case WM_LBUTTONUP:
			ReleaseCapture();

		case WM_KILLFOCUS: 
			dragging = false;
			break;

		// ==========

		case WM_RBUTTONUP:
			ReleaseCapture();

		case WM_NCRBUTTONUP:
			ShowMyMenu(true);
			break;

		case WM_CLOSE:
			break;

		// bring window into foreground on sizing/moving-start
		case WM_NCLBUTTONDOWN:
			SetWindowPos(hwnd, HWND_TOP, 0,0,0,0, SWP_NOSIZE|SWP_NOMOVE);
			UpdateWindow(hwnd);
			// fall through
 		// ==========
		default:
			return DefWindowProc(hwnd,message,wParam,lParam);
	}
	return 0;
}
Пример #30
0
void DeinitIEEE1394(void){
	TerminateThread(iLinkIntrCBThreadID);
	DeleteThread(iLinkIntrCBThreadID);
	DeleteEventFlag(sbp2_event_flag);
}