DWORD WINAPI WriteThreadProc(LPVOID lpParameter) 
{
	HANDLE hFile = HANDLE(lpParameter);
	do 
	{
		WriteBuffer* write_buffer = NULL;
		bool exit = false;
		EnterCriticalSection(&g_write_queue_cs);
		if (g_write_queue.size() > 0) 
		{
			write_buffer = g_write_queue.front();
			g_write_queue.pop();
			g_total_bytes_written += write_buffer->useful_data_size_;
		}
		else if (g_done)
		{
			exit = true;
		} 
		SetEvent(g_write_queue_accepts_more_data_event);
		LeaveCriticalSection(&g_write_queue_cs);

		if (write_buffer) 
		{
			/* DWORD bytes_written = 0;
			::WriteFile(hFile, write_buffer->ptr_, write_buffer->useful_data_size_, 
				&bytes_written, NULL); */
			delete write_buffer;
		} 
		else if (exit) {
			break;
		} else {
			// Wait for new(s).
			WaitForSingleObject(g_write_queue_has_more_data_event, INFINITE);
		}

	} while (true);

	return 1;
}
Example #2
0
pnm
pnm_load(char *path)
{
    FILE *input = L_r_open(path);
    pnm self = NULL;

    HANDLE(any, self = L_load(input));
    fclose(input);

    if (EXCEPTION_RAISED(any))
    {
	if (self != NULL)
	    memory_free(self);

	if (EXCEPTION_RAISED(get_int))
	    RAISE(error, "Truncated pnm file");

	if (EXCEPTION_RAISED(any))
	    RAISE_AGAIN();
    }
    return self;
}
Example #3
0
File: timer.c Project: iyedb/pyuv
static void
on_timer_callback(uv_timer_t *handle)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    Timer *self;
    PyObject *result;

    ASSERT(handle);
    self = PYUV_CONTAINER_OF(handle, Timer, timer_h);

    /* Object could go out of scope in the callback, increase refcount to avoid it */
    Py_INCREF(self);

    result = PyObject_CallFunctionObjArgs(self->callback, self, NULL);
    if (result == NULL) {
        handle_uncaught_exception(HANDLE(self)->loop);
    }
    Py_XDECREF(result);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
Example #4
0
static void
on_pipe_read2(uv_pipe_t* handle, int nread, uv_buf_t buf, uv_handle_type pending)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    uv_err_t err;
    Stream *self;
    PyObject *result, *data, *py_errorno, *py_pending;
    ASSERT(handle);

    self = (Stream *)handle->data;
    ASSERT(self);
    /* Object could go out of scope in the callback, increase refcount to avoid it */
    Py_INCREF(self);

    py_pending = PyInt_FromLong((long)pending);

    if (nread >= 0) {
        data = PyBytes_FromStringAndSize(buf.base, nread);
        py_errorno = Py_None;
        Py_INCREF(Py_None);
    } else {
        data = Py_None;
        Py_INCREF(Py_None);
        err = uv_last_error(UV_HANDLE_LOOP(self));
        py_errorno = PyInt_FromLong((long)err.code);
    }

    result = PyObject_CallFunctionObjArgs(self->on_read_cb, self, data, py_pending, py_errorno, NULL);
    if (result == NULL) {
        handle_uncaught_exception(HANDLE(self)->loop);
    }
    Py_XDECREF(result);
    Py_DECREF(data);
    Py_DECREF(py_pending);
    Py_DECREF(py_errorno);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
Example #5
0
bool   SockPool::InitalWriteQueue(HANDLE WriteQueue, PM &pWriteQueue)
{
	pWriteQueue = (PM)MapViewOfFile(WriteQueue, FILE_MAP_WRITE, 0, 0, sizeof(Manager));///<映射写队列控制块到本地
	if (pWriteQueue == NULL)
		return PrintLog(_T("写控制块映射失败"), false);
	pWriteQueue->hid = 0;   ///<初始化写控制块参数
	pWriteQueue->cid = 0;
	pWriteQueue->writer = _getpid();
	pWriteQueue->Cur = NULL;

	HANDLE EmptyNode = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE, 0, sizeof(Node), NULL);///<创建一个空节点
	PN pNode = (PN)MapViewOfFile(EmptyNode, FILE_MAP_WRITE, 0, 0, sizeof(Node));///<映射节点到本地
	memset(pNode, 0, sizeof(Node));
	UnmapViewOfFile(pNode);

	DuplicateHandle(SH, EmptyNode, SH, &pWriteQueue->Tail, NULL, true, DUPLICATE_SAME_ACCESS); ///<空节点加入链表
	DuplicateHandle(SH, EmptyNode, SH, &pWriteQueue->Head, NULL, true, DUPLICATE_SAME_ACCESS);
	CloseHandle(EmptyNode);
	if (!(pWriteQueue->Tail || pWriteQueue->Head))
		return PrintLog(_T("控制管理块初始化失败"), false);
	return true;
}
Example #6
0
x4s_buf x4_ike_select_prime(uint16 v)
{
  x4s_buf r = { 0 };

  #define HANDLE(bits) \
    case x4c_ike_a1g_modp_##bits : \
      x4_buf_attach(&r,x4v_ike_modp##bits,sizeof(x4v_ike_modp##bits)); \
      break;

  switch (v)
  {
  HANDLE(768);
  HANDLE(1024);
  HANDLE(1536);
  HANDLE(2048);
  HANDLE(3072);
  HANDLE(4096);
  HANDLE(6144);
  HANDLE(8192);
  }
  return r;

  #undef HANDLE
}
Example #7
0
void
iq_add_handlers(void)
{
    xmpp_conn_t * const conn = connection_get_conn();
    xmpp_ctx_t * const ctx = connection_get_ctx();

    HANDLE(NULL,                STANZA_TYPE_ERROR,  _error_handler);

    HANDLE(XMPP_NS_DISCO_INFO,  STANZA_TYPE_GET,    _disco_info_get_handler);
    HANDLE(XMPP_NS_DISCO_INFO,  STANZA_TYPE_RESULT, _disco_info_result_handler);

    HANDLE(XMPP_NS_DISCO_ITEMS, STANZA_TYPE_GET,    _disco_items_get_handler);
    HANDLE(XMPP_NS_DISCO_ITEMS, STANZA_TYPE_RESULT, _disco_items_result_handler);

    HANDLE(STANZA_NS_VERSION,   STANZA_TYPE_GET,    _version_get_handler);
    HANDLE(STANZA_NS_VERSION,   STANZA_TYPE_RESULT, _version_result_handler);

    HANDLE(STANZA_NS_PING,      STANZA_TYPE_GET,    _ping_get_handler);

    if (prefs_get_autoping() != 0) {
        int millis = prefs_get_autoping() * 1000;
        xmpp_timed_handler_add(conn, _ping_timed_handler, millis, ctx);
    }
}
Example #8
0
void CFile::open(const STRING &fileName, CONST UINT mode)
{
	if (m_hFile != HFILE_ERROR)
	{
		CloseHandle(HANDLE(m_hFile));
	}
	m_filename = fileName;

	DWORD access = GENERIC_READ;
	if (mode & OF_WRITE) access |= GENERIC_WRITE;

	DWORD creation = (mode & OF_CREATE) ? CREATE_ALWAYS : OPEN_EXISTING;

	m_hFile = (HFILE)CreateFile(resolve(fileName).c_str(),
		access,
		FILE_SHARE_READ,
		NULL,
		creation,
		FILE_ATTRIBUTE_NORMAL,
		NULL);        

	memset(&m_ptr, 0, sizeof(m_ptr));
}
Example #9
0
/**
* @author ACM2012
* @param [in] pNode新创建的节点句柄,SockMark套接字唯一标示符
* @note    函数的主要功能是将类中缓存的接收到的数据打包到新创建的节点
*/
bool   SockPool::SockDataToNode(PN pNode, unsigned int SockMark)///<将数据打包成节点形式
{
	bool tmpflag = true;
	transstruct *psockstruct = SockMark2SockStruct[SockMark];
	memcpy(pNode->dstip, psockstruct->dstip, 20);///<填充字段
	memcpy(pNode->srcip, psockstruct->srcip, 20);
	pNode->dstport = psockstruct->dstport;
	pNode->srcport = psockstruct->srcport;
	pNode->DataLen = psockstruct->datalength;
	pNode->FuncID = psockstruct->function;
	CString myid;
	myid.Format(_T("%d"), pNode->FuncID);
	//AfxMessageBox(myid);
	if (pNode->FuncID == SOCKSEND || pNode->FuncID == SOCKSENDTO)
		pNode->Data = CreateFileMapping(HANDLE(0xFFFFFFFF), NULL, PAGE_READWRITE, 0, pNode->DataLen, NULL);
	if (pNode->FuncID == SOCKCLOSE)
		tmpflag = false;
	void  *pData = (void *)MapViewOfFile(pNode->Data, FILE_MAP_WRITE, 0, 0, pNode->DataLen);
	if (psockstruct->data!=NULL)
	    memcpy(pData, psockstruct->data, pNode->DataLen);///<拷贝数据
	UnmapViewOfFile(pData);
	return tmpflag;
}
void csort(int *array, int size)
{
	/* int tmp[RANGE + 1] = {0}; */
	pthread_t *workers[WORKER_THREADS];
	args_t *args[WORKER_THREADS];
	int chunk_size = size / WORKER_THREADS;
	int end = 0;
	int i;
	
	/* initialize the tmp array */
	for(i = 0; i < RANGE + 1; i++){
		sem_init(&tmp[i], 0, 0);
	}

	/* partition the work */
	for(i = 0; i < WORKER_THREADS; i ++){
		end = i == WORKER_THREADS - 1 ? size : (i + 1) * chunk_size;
		args[i] = make_args(&array, i * chunk_size, end);
		workers[i] = malloc(sizeof(pthread_t));
		HANDLE(pthread_create(workers[i], NULL, populate_tmp_p, args[i]));
	}

	/* wait for everything to finish */
	for(i = 0; i < WORKER_THREADS; i++){
		pthread_join(*workers[i], NULL);
	}

	/* writeback, sequentially */
	unroll_tmp(&array, RANGE);

	/* free everything */
//	for(i = 0; i < WORKER_THREADS; i++){
//		free_args(args[i]);
		/* pthread_destroy(workers[i]); */
//	}

}
DWORD WINAPI WriteThreadProc(LPVOID lpParameter) 
{
	HANDLE hFile = HANDLE(lpParameter);
	do 
	{
		WriteBuffer* write_buffer = NULL;
		bool exit = false;
		EnterCriticalSection(&g_write_queue_cs);
		if (g_write_queue.size() > 0) 
		{
			write_buffer = g_write_queue.front();
			g_write_queue.pop();
		}
		else if (g_done)
		{
			exit = true;
		} 
		LeaveCriticalSection(&g_write_queue_cs);

		if (write_buffer) 
		{
			DWORD bytes_written = 0;
			::WriteFile(hFile, write_buffer->ptr_, write_buffer->useful_data_size_, 
				&bytes_written, NULL);
			delete write_buffer;
		} 
		else if (exit) {
			break;
		} else {
			::Sleep(0);
		}

	} while (true);

	return 1;
}
Example #12
0
static void
on_pipe_client_connection(uv_connect_t *req, int status)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    Pipe *self;
    PyObject *callback, *result, *py_errorno;
    ASSERT(req);

    self = (Pipe *)req->handle->data;
    callback = (PyObject *)req->data;

    ASSERT(self);

    if (status != 0) {
        uv_err_t err = uv_last_error(UV_HANDLE_LOOP(self));
        py_errorno = PyInt_FromLong(err.code);
    } else {
        py_errorno = Py_None;
        Py_INCREF(Py_None);
    }

    result = PyObject_CallFunctionObjArgs(callback, self, py_errorno, NULL);
    if (result == NULL) {
        handle_uncaught_exception(HANDLE(self)->loop);
    }
    Py_XDECREF(result);
    Py_DECREF(py_errorno);

    Py_DECREF(callback);
    PyMem_Free(req);

    /* Refcount was increased in the caller function */
    Py_DECREF(self);

    PyGILState_Release(gstate);
}
Example #13
0
static void
on_check_callback(uv_check_t *handle, int status)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    Check *self;
    PyObject *result;

    ASSERT(handle);
    ASSERT(status == 0);

    self = (Check *)handle->data;
    ASSERT(self);
    /* Object could go out of scope in the callback, increase refcount to avoid it */
    Py_INCREF(self);

    result = PyObject_CallFunctionObjArgs(self->callback, self, NULL);
    if (result == NULL) {
        handle_uncaught_exception(HANDLE(self)->loop);
    }
    Py_XDECREF(result);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
Example #14
0
File: udp.c Project: ayanamist/pyuv
static int
UDP_tp_init(UDP *self, PyObject *args, PyObject *kwargs)
{
    int r;
    Loop *loop;

    UNUSED_ARG(kwargs);

    RAISE_IF_HANDLE_INITIALIZED(self, -1);

    if (!PyArg_ParseTuple(args, "O!:__init__", &LoopType, &loop)) {
        return -1;
    }

    r = uv_udp_init(loop->uv_loop, (uv_udp_t *)UV_HANDLE(self));
    if (r != 0) {
        RAISE_UV_EXCEPTION(loop->uv_loop, PyExc_UDPError);
        return -1;
    }

    initialize_handle(HANDLE(self), loop);

    return 0;
}
Example #15
0
File: timer.c Project: iyedb/pyuv
static int
Timer_tp_init(Timer *self, PyObject *args, PyObject *kwargs)
{
    int err;
    Loop *loop;

    UNUSED_ARG(kwargs);

    RAISE_IF_HANDLE_INITIALIZED(self, -1);

    if (!PyArg_ParseTuple(args, "O!:__init__", &LoopType, &loop)) {
        return -1;
    }

    err = uv_timer_init(loop->uv_loop, &self->timer_h);
    if (err < 0) {
        RAISE_UV_EXCEPTION(err, PyExc_TimerError);
        return -1;
    }

    initialize_handle(HANDLE(self), loop);

    return 0;
}
Example #16
0
static toff_t
tiff_seek (thandle_t handle, toff_t offset, int whence)
{
	Handle    *h = HANDLE (handle);
	GSeekType  seek_type;

	seek_type = G_SEEK_SET;
        switch (whence) {
        case SEEK_SET:
        	seek_type = G_SEEK_SET;
                break;
        case SEEK_CUR:
        	seek_type = G_SEEK_CUR;
                break;
        case SEEK_END:
        	seek_type = G_SEEK_END;
                break;
        }

	if (! g_seekable_seek (G_SEEKABLE (h->istream), offset, seek_type, h->cancellable, NULL))
		return -1;

	return g_seekable_tell (G_SEEKABLE (h->istream));
}
Example #17
0
static void
dump_thread(void *arg)
{
    HANDLE dbghelp;
    BOOL (WINAPI *pSymInitialize)(HANDLE, const char *, BOOL);
    BOOL (WINAPI *pSymCleanup)(HANDLE);
    BOOL (WINAPI *pStackWalk64)(DWORD, HANDLE, HANDLE, STACKFRAME64 *, void *, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
    DWORD64 (WINAPI *pSymGetModuleBase64)(HANDLE, DWORD64);
    BOOL (WINAPI *pSymFromAddr)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *);
    BOOL (WINAPI *pSymGetLineFromAddr64)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *);
    HANDLE (WINAPI *pOpenThread)(DWORD, BOOL, DWORD);
    DWORD tid = *(DWORD *)arg;
    HANDLE ph;
    HANDLE th;

    dbghelp = LoadLibrary("dbghelp.dll");
    if (!dbghelp) return;
    pSymInitialize = (BOOL (WINAPI *)(HANDLE, const char *, BOOL))GetProcAddress(dbghelp, "SymInitialize");
    pSymCleanup = (BOOL (WINAPI *)(HANDLE))GetProcAddress(dbghelp, "SymCleanup");
    pStackWalk64 = (BOOL (WINAPI *)(DWORD, HANDLE, HANDLE, STACKFRAME64 *, void *, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64))GetProcAddress(dbghelp, "StackWalk64");
    pSymGetModuleBase64 = (DWORD64 (WINAPI *)(HANDLE, DWORD64))GetProcAddress(dbghelp, "SymGetModuleBase64");
    pSymFromAddr = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD64 *, SYMBOL_INFO *))GetProcAddress(dbghelp, "SymFromAddr");
    pSymGetLineFromAddr64 = (BOOL (WINAPI *)(HANDLE, DWORD64, DWORD *, IMAGEHLP_LINE64 *))GetProcAddress(dbghelp, "SymGetLineFromAddr64");
    pOpenThread = (HANDLE (WINAPI *)(DWORD, BOOL, DWORD))GetProcAddress(GetModuleHandle("kernel32.dll"), "OpenThread");
    if (pSymInitialize && pSymCleanup && pStackWalk64 && pSymGetModuleBase64 &&
	pSymFromAddr && pSymGetLineFromAddr64 && pOpenThread) {
	SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_DEBUG | SYMOPT_LOAD_LINES);
	ph = GetCurrentProcess();
	pSymInitialize(ph, NULL, TRUE);
	th = pOpenThread(THREAD_SUSPEND_RESUME|THREAD_GET_CONTEXT, FALSE, tid);
	if (th) {
	    if (SuspendThread(th) != (DWORD)-1) {
		CONTEXT context;
		memset(&context, 0, sizeof(context));
		context.ContextFlags = CONTEXT_FULL;
		if (GetThreadContext(th, &context)) {
		    char libpath[MAX_PATH];
		    char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
		    SYMBOL_INFO *info = (SYMBOL_INFO *)buf;
		    DWORD mac;
		    STACKFRAME64 frame;
		    memset(&frame, 0, sizeof(frame));
#if defined(_M_AMD64) || defined(__x86_64__)
		    mac = IMAGE_FILE_MACHINE_AMD64;
		    frame.AddrPC.Mode = AddrModeFlat;
		    frame.AddrPC.Offset = context.Rip;
		    frame.AddrFrame.Mode = AddrModeFlat;
		    frame.AddrFrame.Offset = context.Rbp;
		    frame.AddrStack.Mode = AddrModeFlat;
		    frame.AddrStack.Offset = context.Rsp;
#elif defined(_M_IA64) || defined(__ia64__)
		    mac = IMAGE_FILE_MACHINE_IA64;
		    frame.AddrPC.Mode = AddrModeFlat;
		    frame.AddrPC.Offset = context.StIIP;
		    frame.AddrBStore.Mode = AddrModeFlat;
		    frame.AddrBStore.Offset = context.RsBSP;
		    frame.AddrStack.Mode = AddrModeFlat;
		    frame.AddrStack.Offset = context.IntSp;
#else	/* i386 */
		    mac = IMAGE_FILE_MACHINE_I386;
		    frame.AddrPC.Mode = AddrModeFlat;
		    frame.AddrPC.Offset = context.Eip;
		    frame.AddrFrame.Mode = AddrModeFlat;
		    frame.AddrFrame.Offset = context.Ebp;
		    frame.AddrStack.Mode = AddrModeFlat;
		    frame.AddrStack.Offset = context.Esp;
#endif

		    while (pStackWalk64(mac, ph, th, &frame, &context, NULL,
					NULL, NULL, NULL)) {
			DWORD64 addr = frame.AddrPC.Offset;
			IMAGEHLP_LINE64 line;
			DWORD64 displacement;
			DWORD tmp;

			if (addr == frame.AddrReturn.Offset || addr == 0 ||
			    frame.AddrReturn.Offset == 0)
			    break;

			memset(buf, 0, sizeof(buf));
			info->SizeOfStruct = sizeof(SYMBOL_INFO);
			info->MaxNameLen = MAX_SYM_NAME;
			if (pSymFromAddr(ph, addr, &displacement, info)) {
			    if (GetModuleFileName((HANDLE)(uintptr_t)pSymGetModuleBase64(ph, addr), libpath, sizeof(libpath)))
				fprintf(stderr, "%s", libpath);
			    fprintf(stderr, "(%s+0x%I64x)",
				    info->Name, displacement);
			}
			fprintf(stderr, " [0x%p]", (void *)(VALUE)addr);
			memset(&line, 0, sizeof(line));
			line.SizeOfStruct = sizeof(line);
			if (pSymGetLineFromAddr64(ph, addr, &tmp, &line))
			    fprintf(stderr, " %s:%lu", line.FileName, line.LineNumber);
			fprintf(stderr, "\n");
		    }
		}

		ResumeThread(th);
	    }
	    CloseHandle(th);
	}
	pSymCleanup(ph);
    }
    FreeLibrary(dbghelp);
}
BOOL COXFileWatcher::AddWatch(LPCTSTR pszPath, BOOL bWatchSubtree, DWORD dwWatchFilter)
{
#if defined (_WINDLL)
#if defined (_AFXDLL)
	AFX_MANAGE_STATE(AfxGetAppModuleState());
#else
	AFX_MANAGE_STATE(AfxGetStaticModuleState());
#endif
#endif

	ASSERT(pszPath != NULL);

	// Clear error flag
	m_hrError = ERROR_SUCCESS;

	COXWatchedDir* pwdNewEntry;

	// Make the class a Thread-Safe Class
	CSingleLock lockObj(&m_crArrayWatchedDirGuard);
	VERIFY(lockObj.Lock());

	// Fisrt check if we are not watching for the same path
	for(int i=0; i<m_arWatchedDirs.GetSize(); i++)
	{
		if((m_arWatchedDirs[i])->m_sPath == pszPath)
		{
			// ... OK. The path is already here
			COXWatchedDir* pwdPresentEntry = m_arWatchedDirs[i];

			if(bWatchSubtree == pwdPresentEntry->m_bWatchSubTree &&
			   dwWatchFilter == pwdPresentEntry->m_dwWatchFilter)
			{
				// No modifications
				return TRUE;
			}

			pwdNewEntry = new COXWatchedDir(
				pszPath,										// directory to be watched
				bWatchSubtree|pwdPresentEntry->m_bWatchSubTree,	// flag for monitoring directory or directory tree 
				dwWatchFilter|pwdPresentEntry->m_dwWatchFilter,	// filter conditions to watch for
				IsExtendedInfoSupported());						// flag for extended info

			// Create new handle
			if(!pwdNewEntry->FindFirstHandle(m_hrError))
			{
				goto error;
			}

			// Prepares the handles for the watcher thread
			m_pNewHandles = m_pHandles;

			VERIFY(m_mxThreadCanContinue.Lock());
			// Informs the watcher thread that it can change the handles
			// and waits for the watcher thread to stop
			VERIFY(m_mxThreadShouldStop.Unlock());
			// wait until the watcher thread stops
			VERIFY(m_mxThreadStopped.Lock());

			// Update the entry for the given path
			m_arWatchedDirs.SetAt(i, pwdNewEntry);

			// Close old entry. This will close the old handle
			delete pwdPresentEntry;

			// Replace the old handle with the new one and start the 
			// thread again
			m_pHandles[i+1]=pwdNewEntry->m_hEvent;

			VERIFY(m_mxThreadStopped.Unlock());
			VERIFY(m_mxThreadShouldStop.Lock());
			// notify watcher thread that it can go on executing
			VERIFY(m_mxThreadCanContinue.Unlock());

			return TRUE;
		}
	}

	pwdNewEntry = new COXWatchedDir(pszPath,		// directory to be watched
									bWatchSubtree,	// flag for monitoring directory or directory tree 
									dwWatchFilter,	// filter conditions to watch for
									IsExtendedInfoSupported());// flag for extended info

	if(pwdNewEntry->FindFirstHandle(m_hrError))
	{
		// Handles are m_nNumHandles, so we must allocate (m_nNumHandles+2) : one for the StartStopEvent
		// and one for the new entry
		m_pNewHandles= new HANDLE[m_nNumHandles + 2];
		// Informs the watcher thread that it can change the handles
		if(m_bThreadIsRunning) 
		{
			VERIFY(m_mxThreadCanContinue.Lock());
			// notify watcher thread that it should stop
			VERIFY(m_mxThreadShouldStop.Unlock());
			// wait until it stops

			DWORD dwResult=::WaitForSingleObject(m_mxThreadStopped.m_hObject, 0xFFFFFFFF);
			ASSERT(dwResult==NULL);
			//VERIFY(m_mxThreadStopped.Lock());
		}

		// update the array of directories
		m_arWatchedDirs.Add(pwdNewEntry);

		if(0 < m_nNumHandles)
		{
			memcpy(m_pNewHandles,m_pHandles,(m_nNumHandles+1)*sizeof(HANDLE));
		}
		else
		{
			m_pNewHandles[0]=HANDLE(m_mxThreadShouldStop);
		}
		m_pNewHandles[m_nNumHandles+1] = pwdNewEntry->m_hEvent;

		// ... m_pHandles may be NULL
		delete [] m_pHandles;
		m_pHandles = m_pNewHandles;
		m_nNumHandles++;

		// Starts the watcher thread
		if(m_bThreadIsRunning) 
		{
			VERIFY(m_mxThreadStopped.Unlock());
			VERIFY(m_mxThreadShouldStop.Lock());
			// Unlocks the watcher thread
			VERIFY(m_mxThreadCanContinue.Unlock());
			return TRUE;
		}
		else
		{
			// ... m_pWatcherThread may already be NULL
			delete m_pWatcherThread;
			VERIFY(m_eventStartThread.ResetEvent());
			m_pWatcherThread=AfxBeginThread(FileWatchThreadFunction,this);
			if(m_pWatcherThread!=NULL)
			{
				m_pWatcherThread->m_bAutoDelete = FALSE;
				::WaitForSingleObject(m_eventStartThread,INFINITE);
				return TRUE;
			}
		}
	}
	
error:
	delete pwdNewEntry;
	CONDITIONAL_TRACE_RESULT("COXFileWatcher::AddWatch", m_hrError)
	return FALSE;
}
Example #19
0
File: win32.c Project: BossKing/vlc
/*****************************************************************************
 * Thread: main loop
 *****************************************************************************/
static void *Thread( void *p_data )
{
    MSG message;

    intf_thread_t *p_intf = p_data;
    intf_sys_t *p_sys = p_intf->p_sys;

    /* Window which receives Hotkeys */
    vlc_mutex_lock( &p_sys->lock );
    p_sys->hotkeyWindow =
        (void*)CreateWindow( _T("STATIC"),           /* name of window class */
                _T("VLC ghk ") _T(VERSION),         /* window title bar text */
                0,                                           /* window style */
                0,                                   /* default X coordinate */
                0,                                   /* default Y coordinate */
                0,                                           /* window width */
                0,                                          /* window height */
                NULL,                                    /* no parent window */
                NULL,                              /* no menu in this window */
                GetModuleHandle(NULL),    /* handle of this program instance */
                NULL );                                 /* sent to WM_CREATE */

    if( p_sys->hotkeyWindow == NULL )
    {
        p_sys->hotkeyWindow = INVALID_HANDLE_VALUE;
        vlc_cond_signal( &p_sys->wait );
        vlc_mutex_unlock( &p_sys->lock );
        return NULL;
    }
    vlc_cond_signal( &p_sys->wait );
    vlc_mutex_unlock( &p_sys->lock );

    SetWindowLongPtr( p_sys->hotkeyWindow, GWLP_WNDPROC,
            (LONG_PTR)WMHOTKEYPROC );
    SetWindowLongPtr( p_sys->hotkeyWindow, GWLP_USERDATA,
            (LONG_PTR)p_intf );

    /* Registering of Hotkeys */
    for( const struct hotkey *p_hotkey = p_intf->obj.libvlc->p_hotkeys;
            p_hotkey->psz_action != NULL;
            p_hotkey++ )
    {
        char varname[12 + strlen( p_hotkey->psz_action )];
        sprintf( varname, "global-key-%s", p_hotkey->psz_action );

        char *key = var_InheritString( p_intf, varname );
        if( key == NULL )
            continue;

        UINT i_key = vlc_str2keycode( key );
        free( key );
        if( i_key == KEY_UNSET )
            continue;

        UINT i_keyMod = 0;
        if( i_key & KEY_MODIFIER_SHIFT ) i_keyMod |= MOD_SHIFT;
        if( i_key & KEY_MODIFIER_ALT ) i_keyMod |= MOD_ALT;
        if( i_key & KEY_MODIFIER_CTRL ) i_keyMod |= MOD_CONTROL;

#define HANDLE( key ) case KEY_##key: i_vk = VK_##key; break
#define HANDLE2( key, key2 ) case KEY_##key: i_vk = VK_##key2; break

#define KEY_SPACE ' '

#ifndef VK_VOLUME_DOWN
#define VK_VOLUME_DOWN          0xAE
#define VK_VOLUME_UP            0xAF
#endif

#ifndef VK_MEDIA_NEXT_TRACK
#define VK_MEDIA_NEXT_TRACK     0xB0
#define VK_MEDIA_PREV_TRACK     0xB1
#define VK_MEDIA_STOP           0xB2
#define VK_MEDIA_PLAY_PAUSE     0xB3
#endif

#ifndef VK_PAGEUP
#define VK_PAGEUP               0x21
#define VK_PAGEDOWN             0x22
#endif

        UINT i_vk = 0;
        switch( i_key & ~KEY_MODIFIER )
        {
            HANDLE( LEFT );
            HANDLE( RIGHT );
            HANDLE( UP );
            HANDLE( DOWN );
            HANDLE( SPACE );
            HANDLE2( ESC, ESCAPE );
            HANDLE2( ENTER, RETURN );
            HANDLE( F1 );
            HANDLE( F2 );
            HANDLE( F3 );
            HANDLE( F4 );
            HANDLE( F5 );
            HANDLE( F6 );
            HANDLE( F7 );
            HANDLE( F8 );
            HANDLE( F9 );
            HANDLE( F10 );
            HANDLE( F11 );
            HANDLE( F12 );
            HANDLE( PAGEUP );
            HANDLE( PAGEDOWN );
            HANDLE( HOME );
            HANDLE( END );
            HANDLE( INSERT );
            HANDLE( DELETE );
            HANDLE( VOLUME_DOWN );
            HANDLE( VOLUME_UP );
            HANDLE( MEDIA_PLAY_PAUSE );
            HANDLE( MEDIA_STOP );
            HANDLE( MEDIA_PREV_TRACK );
            HANDLE( MEDIA_NEXT_TRACK );

            default:
                i_vk = toupper( (uint8_t)(i_key & ~KEY_MODIFIER) );
                break;
        }
        if( !i_vk ) continue;

#undef HANDLE
#undef HANDLE2

        ATOM atom = GlobalAddAtomA( p_hotkey->psz_action );
        if( !atom ) continue;

        if( !RegisterHotKey( p_sys->hotkeyWindow, atom, i_keyMod, i_vk ) )
            GlobalDeleteAtom( atom );
    }

    /* Main message loop */
    while( GetMessage( &message, NULL, 0, 0 ) )
        DispatchMessage( &message );

    /* Unregistering of Hotkeys */
    for( const struct hotkey *p_hotkey = p_intf->obj.libvlc->p_hotkeys;
            p_hotkey->psz_action != NULL;
            p_hotkey++ )
    {
        ATOM atom = GlobalFindAtomA( p_hotkey->psz_action );
        if( !atom ) continue;

        if( UnregisterHotKey( p_sys->hotkeyWindow, atom ) )
            GlobalDeleteAtom( atom );
    }

    /* close window */
    vlc_mutex_lock( &p_sys->lock );
    DestroyWindow( p_sys->hotkeyWindow );
    p_sys->hotkeyWindow = NULL;
    vlc_mutex_unlock( &p_sys->lock );

    return NULL;
}
Example #20
0
File: win.c Project: jacereda/glcv
static LRESULT WINAPI handle(HWND win, UINT msg, WPARAM w, LPARAM l)  {
        LRESULT r;
        switch (msg) {
#define HANDLE(x) case WM_##x: r = HANDLE_WM_##x(win, w, l, on##x); break
                HANDLE(MOUSEMOVE);
                HANDLE(SIZE);
                HANDLE(CLOSE);
                HANDLE(KEYDOWN);
                HANDLE(SYSKEYDOWN);
                HANDLE(SYSKEYUP);
                HANDLE(CHAR);
                HANDLE(KEYUP);
                HANDLE(LBUTTONDOWN);
                HANDLE(RBUTTONDOWN);
                HANDLE(MBUTTONDOWN);
                HANDLE(LBUTTONUP);
                HANDLE(RBUTTONUP);
                HANDLE(MBUTTONUP);
                HANDLE(MOUSEWHEEL);
                HANDLE(SETCURSOR);
                HANDLE(PAINT);
#undef HANDLE
        default: r = 0;
        }
        if (!r)
                r = DefWindowProcW(win, msg, w, l);
        return r;
}
Example #21
0
//---------------------------------------------------------------------------
// KillProcessTreeWinHelper
//
//  This is a recursive helper function that terminates all the processes
//  started by the specified process and them terminates the process itself
//
//  Parameters:
//	  dwProcessId - identifier of the process to terminate
//
//  Returns:
//	  Win32 error code.
//
static
BOOL
WINAPI
KillProcessTreeWinHelper
(
 IN DWORD dwProcessId
)
{
  HINSTANCE hKernel;
  HANDLE (WINAPI * _CreateToolhelp32Snapshot)(DWORD, DWORD);
  BOOL (WINAPI * _Process32First)(HANDLE, PROCESSENTRY32 *);
  BOOL (WINAPI * _Process32Next)(HANDLE, PROCESSENTRY32 *);

  // get handle to KERNEL32.DLL
  hKernel = GetModuleHandle(_T("kernel32.dll"));
  //  _ASSERTE(hKernel != NULL);

  // locate necessary functions in KERNEL32.DLL
  *(FARPROC *)&_CreateToolhelp32Snapshot =
    GetProcAddress(hKernel, "CreateToolhelp32Snapshot");
  *(FARPROC *)&_Process32First =
    GetProcAddress(hKernel, "Process32First");
  *(FARPROC *)&_Process32Next =
    GetProcAddress(hKernel, "Process32Next");

  if (_CreateToolhelp32Snapshot == NULL ||
      _Process32First == NULL ||
      _Process32Next == NULL)
    return ERROR_PROC_NOT_FOUND;

  HANDLE hSnapshot;
  PROCESSENTRY32 Entry;

  // create a snapshot
  hSnapshot = _CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (hSnapshot == INVALID_HANDLE_VALUE)
    return GetLastError();

  Entry.dwSize = sizeof(Entry);
  if (!_Process32First(hSnapshot, &Entry))
    {
      DWORD dwError = GetLastError();
      CloseHandle(hSnapshot);
      return dwError;
    }

  // kill all children first
  do
    {
      if (Entry.th32ParentProcessID == dwProcessId)
        KillProcessTreeWinHelper(Entry.th32ProcessID);

      Entry.dwSize = sizeof(Entry);
    }
  while (_Process32Next(hSnapshot, &Entry));

  CloseHandle(hSnapshot);

  // kill the process itself
  if (!KillProcess(dwProcessId))
    return GetLastError();

  return ERROR_SUCCESS;
}
Example #22
0
BOOL CMemCommProcess::Open(UINT32 dwSize, BOOL bLock, string &strName)
{

	dwSize = (dwSize + MEMCOMM_ALIGN_BYTE_NUM -1) / MEMCOMM_ALIGN_BYTE_NUM * MEMCOMM_ALIGN_BYTE_NUM + MEMCOMM_ALIGN_BYTE_NUM;
	dwSize = sizeof(StruMemCookie) + dwSize;

#ifdef _WIN32
	m_pMemHandle = CreateFileMapping(HANDLE(-1), NULL, PAGE_READWRITE, 0, dwSize, (LPCWSTR)strName.c_str());
	if (m_pMemHandle == NULL)
		return FALSE;

	if (GetLastError() != ERROR_ALREADY_EXISTS)//不存在
	{
		CloseHandle(m_pMemHandle);
		m_pMemHandle = NULL;
		return FALSE;
	}

	//映射共享内存
	m_pHead = MapViewOfFile(m_pMemHandle, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, dwSize);//创建视
	CloseHandle(m_pMemHandle);
	if (m_pHead == NULL)
	{
		return FALSE;
	}

#endif


#ifdef _LINUX
	
	//获取已经存在共享内存ID
	m_iShareMemID = shmget((key_t)(*(int *)strName.c_str()),0,0);
	if(m_iShareMemID == -1)//表明是重新创建的
	{
		m_pHead = NULL;
		Free();
		return FALSE;
	}

	//获取共享内存地址
	m_pHead = shmat(m_iShareMemID, (void *)0, 0);
	if (m_pHead == (void *) -1)
	{
		m_pHead = NULL;
		Free();
		return FALSE;
	}

#endif

	m_pStruCookie = (StruMemCookie *)m_pHead;

	//创建锁
	if (m_pStruCookie->uiLock == 1)
	{

		if (m_pCGSProcessMutex == NULL)
		{
			m_pCGSProcessMutex = new CGSProcessMutex(m_pStruCookie->chMutexName);
			if (m_pCGSProcessMutex == NULL)
			{

				Free();
				return FALSE;
			}

		}
	}

	return TRUE;
}
Example #23
0
const char* cmuk::getFrameString(int i) {

#define HANDLE(arg) case arg: return #arg

  switch (i) {
    HANDLE(FRAME_GROUND);
    HANDLE(FRAME_TRUNK);
    HANDLE(FRAME_FL_HIP_RX);
    HANDLE(FRAME_FL_HIP_RY);
    HANDLE(FRAME_FL_KNEE_RY);
    HANDLE(FRAME_FL_FOOT);
    HANDLE(FRAME_FR_HIP_RX);
    HANDLE(FRAME_FR_HIP_RY);
    HANDLE(FRAME_FR_KNEE_RY);
    HANDLE(FRAME_FR_FOOT);
    HANDLE(FRAME_HL_HIP_RX);
    HANDLE(FRAME_HL_HIP_RY);
    HANDLE(FRAME_HL_KNEE_RY);
    HANDLE(FRAME_HL_FOOT);
    HANDLE(FRAME_HR_HIP_RX);
    HANDLE(FRAME_HR_HIP_RY);
    HANDLE(FRAME_HR_KNEE_RY);
    HANDLE(FRAME_HR_FOOT);
  default: break;
  }
  return "*** INVALID FRAME ***";

#undef HANDLE

}
Example #24
0
const char* cmuk::getErrorString(int status) {

#define HANDLE(arg) case arg: return #arg

  switch (status) {
    HANDLE(CMUK_OKAY);
    HANDLE(CMUK_BAD_LEG_INDEX);
    HANDLE(CMUK_BAD_JOINT_OFFSET);
    HANDLE(CMUK_ANGLE_OUT_OF_RANGE);
    HANDLE(CMUK_SINGULAR_MATRIX);
    HANDLE(CMUK_INSUFFICIENT_ARGUMENTS);
    HANDLE(CMUK_CANNOT_REACH_IK_KNEE_BENT_FORWARD);
    HANDLE(CMUK_CANNOT_REACH_IK_KNEE_BENT_REARWARD);
    HANDLE(CMUK_CANNOT_REACH_IK_KNEE_BENT_EITHER);
    HANDLE(CMUK_BAD_QUATERNION_VECTOR);
    HANDLE(CMUK_BAD_FRAME_INDEX);
  default: break;
  }
  return "*** INVALID STATUS ***";

#undef HANDLE

}
Example #25
0
/*
==============
Trace_GetHopCount

Performs a synchronous hopcount on the specified server
==============
*/
int Trace_GetHopCount( char *pServer, int nMaxHops )
{
#ifdef _WIN32
	HMODULE					hICMP;			// Handle to ICMP .dll
	HANDLE					hIP;			// Handle to icmp session
	DWORD					*dwIPAddr;		// remote IP Address as a DWORD
	struct hostent			*pHostEnt;		// Name of remote host
	trace_options_t			traceOptions;	// Input options
	int						c;				// Hop counter

	// Prototypes
	HANDLE ( WINAPI *pfnICMPCreateFile ) ( VOID );
	BOOL ( WINAPI *pfnICMPCloseFile ) ( HANDLE );
	DWORD (WINAPI *pfnICMPSendEcho) ( HANDLE, DWORD, LPVOID, WORD, LPVOID, LPVOID, DWORD, DWORD );

	hICMP = ::LoadLibrary( "ICMP.DLL" );
	
	pfnICMPCreateFile	= ( HANDLE ( WINAPI *)(VOID ) )::GetProcAddress( hICMP,"IcmpCreateFile");
	pfnICMPCloseFile	= ( BOOL ( WINAPI *) ( HANDLE ) )::GetProcAddress( hICMP,"IcmpCloseHandle");
	pfnICMPSendEcho		= ( DWORD ( WINAPI * ) ( HANDLE, DWORD, LPVOID, WORD, LPVOID, LPVOID, DWORD,DWORD ) )::GetProcAddress( hICMP,"IcmpSendEcho" );
	
	if ( !pfnICMPCreateFile ||
		 !pfnICMPCloseFile ||
		 !pfnICMPSendEcho )
	{
		return -1;
	}

	hIP = pfnICMPCreateFile();
	if ( !hIP )
	{
		return -1;
	}

	// DNS lookup on remote host
	pHostEnt = gethostbyname( pServer );
	if ( !pHostEnt )
	{
		return -1;
	}

	// Take first IP address returned
	dwIPAddr = ( DWORD * )( *pHostEnt->h_addr_list );

	// Fixme:  If not tracing, can use a "binary search" method to do the trace route
	for ( c = 1; c <= nMaxHops ; c++)
	{
		// Set TTL correctly
		traceOptions.ucTTL = (unsigned char)c;

		// Clear out return structure
		memset( &traceReturn, 0, sizeof( traceReturn ) );

		// Send echo request, 2000 milliseconds maximum waiting time
		pfnICMPSendEcho ( hIP, *dwIPAddr, 0, 0, &traceOptions, &traceReturn, sizeof(traceReturn), 2000 );
		
		// Found requrested remote address, c contains the correct hopcount
		if ( traceReturn.dwAddress == *dwIPAddr )
			break;
	}

	/*
	// This is how you do a raw ping
	npings = 1;
	pfnICMPSendEcho( hIP, *dwIPAddr, 0, 0, NULL, &E, sizeof( E ), 2000 );
	*ping = (double)E.RoundTripTime / 1000.0;
	*/

	// Clean up file and dll handles
	pfnICMPCloseFile( hIP );

	::FreeLibrary( hICMP );

	// Failure?
	if ( c > nMaxHops )
	{
		return -1;
	}

	return c;
#else
	return -1;
#endif
}
Example #26
0
CMenu* CCementBD::SetModulesExtern()
{
	if(gListModuleExternal.GetCount() == 0) return 0;
    //---------------------------------------------------
    //Формируем меню внешних модулей
    CCementDoc* pDoc = (CCementDoc*)GetDocument();
	HINSTANCE hInst = AfxGetResourceHandle();
    pDoc->m_DefaultMenu = 
        ::LoadMenu(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_KRSCEMENTTYPE));
    if (pDoc->m_DefaultMenu == NULL)
        return 0;

    CMenu* menu = CMenu::FromHandle(pDoc->GetDefaultMenu());
    if(menu)
    {
        int iPos;
        CMenu* pPopup = NULL;
        for(iPos = 0; iPos < (int)menu->GetMenuItemCount(); iPos++)
        {
            if(menu->GetSubMenu(iPos)->GetMenuItemID(0) == ID_NASTROIKA_MODULES) 
            {
                pPopup = menu->GetSubMenu(iPos);
 		int ii = (int)pPopup->GetMenuItemCount();
               break;
            }
        }
        if(pPopup == NULL) return 0;


		CMenu *submenu = menu->GetSubMenu(iPos);
		if(submenu == NULL) return 0;
		int ii = (int)submenu->GetMenuItemCount();


        int cx = ::GetSystemMetrics(SM_CXMENUCHECK);
        int cy = ::GetSystemMetrics(SM_CYMENUCHECK);
        if(pPopup != NULL && gListModuleExternal.GetCount() > 0) 
        {
            pPopup->AppendMenu(MF_SEPARATOR, 0, LPCTSTR(0));

            for(int i = 0; i < gListModuleExternal.GetCount(); i++)
            {
                HICON hIconLarge, hIcon;
//                ExtractIconEx(gListModuleExternal.GetName2(i), 0, &hIconLarge, &hIcon, 1);
				CString Name2 = gListModuleExternal.GetName2txe(i);
				if(Name2.GetLength() == 0) continue;
				ExtractIconEx(Name2, 0, &hIconLarge, &hIcon, 1);
                //HICON hIcon = ExtractIcon(pApp->m_hInstance, gListModuleExternal.GetName2(i), 0);
                if(hIcon != NULL)
                {
                    ICONINFO iconinfo;
                    GetIconInfo(hIcon, &iconinfo);
                    HANDLE hLoad = CopyImage(HANDLE(iconinfo.hbmColor), IMAGE_BITMAP, cx+1, cy+1, LR_COPYFROMRESOURCE);
                    CBitmap *pBmp = CBitmap::FromHandle(HBITMAP(hLoad));
                    CString str;
                    str.Format(" %d", i);
                    str += ".  " + gListModuleExternal.GetName(i);
                    BOOL flg = pPopup->AppendMenu(MF_STRING | MF_ENABLED, ID_MENU_MODULE_EXTERNAL + i, str);
                    pPopup->SetMenuItemBitmaps(i+2, MF_BYPOSITION, pBmp, pBmp);
                    //BOOL res = menu->SetMenuItemBitmaps(2, MF_BYPOSITION, pBmp, pBmp);
                    //int zzz = 0;
                }
            }
        }
        CMDIFrameWnd* frame = ((CMDIChildWnd *) GetParent())->GetMDIFrame();
        frame->MDISetMenu(menu, NULL);
        frame->DrawMenuBar();
    }
    //-------------------------------------------------------------------------
	return menu;
}
Example #27
0
 /*! destroy a hardware thread by its handle */
 void destroyThread(thread_t tid) {
   TerminateThread(HANDLE(tid),0);
   CloseHandle(HANDLE(tid));
 }
Example #28
0
static PyObject *
Process_func_spawn(Process *self, PyObject *args, PyObject *kwargs)
{
    int err, flags, len, stdio_count;
    unsigned int uid, gid;
    char *cwd, *cwd2, *file, *file2, *arg_str, *tmp_str, *key_str, *value_str;
    char **ptr, **process_args, **process_env;
    Py_ssize_t i, n, pos;
    PyObject *key, *value, *item, *tmp, *callback, *arguments, *env, *stdio, *ret;
    uv_process_options_t options;
    uv_stdio_container_t *stdio_container;

    static char *kwlist[] = {"file", "exit_callback", "args", "env", "cwd", "uid", "gid", "flags", "stdio", NULL};

    cwd = NULL;
    ptr = process_args = process_env = NULL;
    tmp = arguments = env = stdio = NULL;
    stdio_container = NULL;
    flags = uid = gid = stdio_count = 0;

    RAISE_IF_SPAWNED(self, NULL);

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|OOO!sIIiO:__init__", kwlist, &file, &callback, &arguments, &PyDict_Type, &env, &cwd, &uid, &gid, &flags, &stdio)) {
        return NULL;
    }

    if (callback != Py_None && !PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable is required");
        return NULL;
    }

    if (arguments && !PySequence_Check(arguments)) {
        PyErr_SetString(PyExc_TypeError, "only iterable objects are supported for 'args'");
        return NULL;
    }

    if (stdio && !PySequence_Check(stdio)) {
        PyErr_SetString(PyExc_TypeError, "only iterable objects are supported for 'stdio'");
        return NULL;
    }

    memset(&options, 0, sizeof(uv_process_options_t));

    options.uid = uid;
    options.gid = gid;
    options.flags = flags;
    options.exit_cb = on_process_exit;

    file2 = PyMem_Malloc(strlen(file) + 1);
    if (!file2) {
        PyErr_NoMemory();
        ret = NULL;
        goto cleanup;
    }
    strcpy(file2, file);
    options.file = file2;

    if (arguments) {
        n = PySequence_Length(arguments);
        process_args = PyMem_Malloc(sizeof *process_args * (n + 2));
        if (!process_args) {
            PyErr_NoMemory();
            PyMem_Free(file2);
            ret = NULL;
            goto cleanup;
        }
        process_args[0] = file2;
        i = 0;
        while (i < n) {
            item = PySequence_GetItem(arguments, i);
            if (!item || !PyArg_Parse(item, "s;args contains a non-string value", &arg_str)) {
                Py_XDECREF(item);
                ret = NULL;
                goto cleanup;
            }
            tmp_str = PyMem_Malloc(strlen(arg_str) + 1);
            if (!tmp_str) {
                Py_DECREF(item);
                ret = NULL;
                goto cleanup;
            }
            strcpy(tmp_str, arg_str);
            process_args[i+1] = tmp_str;
            Py_DECREF(item);
            i++;
        }
        process_args[i+1] = NULL;
    } else {
        process_args = PyMem_Malloc(sizeof *process_args * 2);
        if (!process_args) {
            PyErr_NoMemory();
            PyMem_Free(file2);
            ret = NULL;
            goto cleanup;
        }
        process_args[0] = file2;
        process_args[1] = NULL;
    }
    options.args = process_args;

    if (cwd) {
        cwd2 = PyMem_Malloc(strlen(cwd) + 1);
        if (!cwd2) {
            PyErr_NoMemory();
            ret = NULL;
            goto cleanup;
        }
        strcpy(cwd2, cwd);
        options.cwd = cwd2;
    }

    if (env) {
        n = PyDict_Size(env);
        if (n > 0) {
            process_env = PyMem_Malloc(sizeof *process_env * (n + 1));
            if (!process_env) {
                PyErr_NoMemory();
                ret = NULL;
                goto cleanup;
            }
            i = 0;
            pos = 0;
            while (PyDict_Next(env, &pos, &key, &value)) {
                if (!PyArg_Parse(key, "s;env contains a non-string key", &key_str) || !PyArg_Parse(value, "s;env contains a non-string value", &value_str)) {
                    ret = NULL;
                    goto cleanup;
                }
                len = strlen(key_str) + strlen(value_str) + 2;
                tmp_str = PyMem_Malloc(len);
                if (!tmp_str) {
                    PyErr_NoMemory();
                    ret = NULL;
                    goto cleanup;
                }
                PyOS_snprintf(tmp_str, len, "%s=%s", key_str, value_str);
                process_env[i] = tmp_str;
                i++;
            }
            process_env[i] = NULL;
        }
    }
    options.env = process_env;

    if (stdio) {
        n = PySequence_Length(stdio);
        stdio_container = PyMem_Malloc(sizeof *stdio_container * n);
        if (!stdio_container) {
            PyErr_NoMemory();
            ret = NULL;
            goto cleanup;
        }
        item = NULL;
        for (i = 0;i < n; i++) {
            item = PySequence_GetItem(stdio, i);
            if (!item || !PyObject_TypeCheck(item, &StdIOType)) {
                Py_XDECREF(item);
                PyErr_SetString(PyExc_TypeError, "a StdIO instance is required");
                ret = NULL;
                goto cleanup;
            }
            stdio_count++;
            stdio_container[i].flags = ((StdIO *)item)->flags;
            if (((StdIO *)item)->flags & (UV_CREATE_PIPE | UV_INHERIT_STREAM)) {
                stdio_container[i].data.stream = (uv_stream_t *)(UV_HANDLE(((StdIO *)item)->stream));
            } else if (((StdIO *)item)->flags & UV_INHERIT_FD) {
                stdio_container[i].data.fd = ((StdIO *)item)->fd;
            }
            Py_DECREF(item);
        }
    }
    options.stdio = stdio_container;
    options.stdio_count = stdio_count;

    err = uv_spawn(UV_HANDLE_LOOP(self), &self->process_h, &options);
    if (err < 0) {
        RAISE_UV_EXCEPTION(err, PyExc_ProcessError);
        ret = NULL;
        goto cleanup;
    }

    tmp = (PyObject *)self->on_exit_cb;
    Py_INCREF(callback);
    self->on_exit_cb = callback;
    Py_XDECREF(tmp);

    tmp = self->stdio;
    Py_XINCREF(stdio);
    self->stdio = stdio;
    Py_XDECREF(tmp);

    HANDLE(self)->initialized = True;
    self->spawned = True;

    ret = Py_None;

    /* Increase refcount so that object is not removed before the exit callback is called */
    Py_INCREF(self);

cleanup:
    if (options.args) {
        for (ptr = options.args; *ptr != NULL; ptr++) {
            PyMem_Free(*ptr);
        }
    }

    if (options.env) {
        for (ptr = options.env; *ptr != NULL; ptr++) {
            PyMem_Free(*ptr);
        }
    }

    PyMem_Free(options.args);
    PyMem_Free(options.cwd);
    PyMem_Free(options.env);
    PyMem_Free(options.stdio);

    Py_XINCREF(ret);
    return ret;
}
Example #29
0
static void
Process_tp_dealloc(Process *self)
{
    HANDLE(self)->initialized = self->spawned;
    HandleType.tp_dealloc((PyObject *)self);
}
Example #30
0
 /*! waits until the given thread has terminated */
 void join(thread_t tid) {
   WaitForSingleObject(HANDLE(tid), INFINITE);
   CloseHandle(HANDLE(tid));
 }