这篇教程C++ CloseHandle函数代码示例写得很实用,希望能帮到您。
本文整理汇总了C++中CloseHandle函数的典型用法代码示例。如果您正苦于以下问题:C++ CloseHandle函数的具体用法?C++ CloseHandle怎么用?C++ CloseHandle使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。 在下文中一共展示了CloseHandle函数的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。 示例1: CloseHandlegcore::Condition::~Condition() { details::COND_WIN32 *cond = (details::COND_WIN32*)(&mData[0]); CloseHandle(cond->notifyOne); CloseHandle(cond->notifyAll); DeleteCriticalSection(&(cond->blockedLock));}
开发者ID:gatgui,项目名称:gcore,代码行数:6,
示例2: is_guistatic int is_gui(const char *exename){ HANDLE hImage; DWORD bytes; DWORD SectionOffset; DWORD CoffHeaderOffset; DWORD MoreDosHeader[16]; ULONG ntSignature; IMAGE_DOS_HEADER image_dos_header; IMAGE_FILE_HEADER image_file_header; IMAGE_OPTIONAL_HEADER image_optional_header; hImage = CreateFile(exename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hImage) { return 0; } /* * Read the MS-DOS image header. */ if (!ReadFile(hImage, &image_dos_header, sizeof(IMAGE_DOS_HEADER), &bytes, NULL)) { CloseHandle(hImage); return 0; } if (IMAGE_DOS_SIGNATURE != image_dos_header.e_magic) { CloseHandle(hImage); return 0; } /* Read more MS-DOS header */ if (!ReadFile(hImage, MoreDosHeader, sizeof(MoreDosHeader), &bytes, NULL)) { CloseHandle(hImage); return 0; } /* Get actual COFF header. */ CoffHeaderOffset = SetFilePointer(hImage, image_dos_header.e_lfanew, NULL, FILE_BEGIN); if (CoffHeaderOffset == (DWORD)(-1)) { CloseHandle(hImage); return 0; } CoffHeaderOffset += sizeof(ULONG); if (!ReadFile (hImage, &ntSignature, sizeof(ULONG), &bytes, NULL)) { CloseHandle(hImage); return 0; } if (IMAGE_NT_SIGNATURE != ntSignature) { CloseHandle(hImage); return 0; } SectionOffset = CoffHeaderOffset + IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_NT_OPTIONAL_HEADER; if (!ReadFile(hImage, &image_file_header, IMAGE_SIZEOF_FILE_HEADER, &bytes, NULL)) { CloseHandle(hImage); return 0; } /* Read optional header. */ if (!ReadFile(hImage, &image_optional_header, IMAGE_SIZEOF_NT_OPTIONAL_HEADER, &bytes, NULL)) { CloseHandle(hImage); return 0; } CloseHandle(hImage); if (image_optional_header.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) return 1; return 0;}
开发者ID:oldfaber,项目名称:wzsh,代码行数:76,
示例3: process_shebangstatic int process_shebang(char *argv0, const char *const *cmdstr, size_t *cmdlen, char **cmdend, unsigned int *cmdsize){ HANDLE hfile; char buf[512]; unsigned int nn, t0; char *ptr, *ptr2; char *newargv[4]; char pbuffer[MAX_PATH]; char *filepart; static const char *shellnames[] = {"/bin/sh", "/bin/zsh", "/bin/ksh"}; static const char usrbinenv[] = "/usr/bin/env"; static const char usrbinpython[] = "/usr/bin/python"; static const char usrbinperl[] = "/usr/bin/perl"; static const char usrbintcl[] = "/usr/bin/tcl"; hfile = CreateFile(argv0, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hfile == INVALID_HANDLE_VALUE) return (-1); if (!ReadFile(hfile, buf, (DWORD)sizeof(buf), (DWORD *)&nn, NULL)) { CloseHandle(hfile); return (-1); } CloseHandle(hfile); if (!((nn >= 3) && (buf[0] == '#') && (buf[1] == '!'))) return (0); /* this code is more or less what zexecve() does */ for (t0 = 0; t0 != nn; t0++) if ((buf[t0] == '/n') || (buf[t0] == '/r')) break; while (isspace(buf[t0])) buf[t0--] = '/0'; buf[sizeof(buf)-1] = '/0'; /* @@@@ fails for "/b/s p/pgm" !!! */ for (ptr = buf + 2; *ptr && *ptr == ' '; ptr++) ; for (ptr2 = ptr; *ptr && *ptr != ' '; ptr++) ; /* ptr2 is the program name, ptr points to the args */ dbgprintf(PR_VERBOSE, "%s(): found /"!#/" program=[%s] arg ptr=[%s]/n", __FUNCTION__, ptr2, *ptr ? ptr + 1 : "NULL"); /* append to the cmdstr should have argv0 ('/' or '/' format ?) */ if (*ptr) { *ptr = '/0'; newargv[0] = ptr2; newargv[1] = ptr + 1; newargv[2] = argv0; } else { newargv[0] = ptr2; newargv[1] = argv0; newargv[2] = NULL; } newargv[3] = NULL; concat_args_and_quote((const char *const *)newargv, (char **)cmdstr, cmdlen, cmdend, cmdsize); *cmdend = '/0'; /* if ptr2 is a "well known" shell name set argv0 to our module name */ for (nn = 0; nn < LENGTH_OF(shellnames); nn++) { if (strcmp(ptr2, shellnames[nn]) == 0) { strcpy(argv0, gModuleName); return (1); } } if (strcmp(ptr2, usrbinenv) == 0) { SearchPath(NULL, "env.exe", NULL, sizeof(pbuffer), pbuffer, &filepart); strcpy(argv0, pbuffer); } else if (strcmp(ptr2, usrbinpython) == 0) { SearchPath(NULL, "python.exe", NULL, sizeof(pbuffer), pbuffer, &filepart); strcpy(argv0, pbuffer); } else if (strcmp(ptr2, usrbinperl) == 0) { SearchPath(NULL, "perl.exe", NULL, sizeof(pbuffer), pbuffer, &filepart); strcpy(argv0, pbuffer); } else if (strcmp(ptr2, usrbintcl) == 0) { SearchPath(NULL, "tcl.exe", NULL, sizeof(pbuffer), pbuffer, &filepart); strcpy(argv0, pbuffer); } else { char *exeptr; path_to_backslash(ptr2); strcpy(argv0, ptr2); /* if argv0 does not end with ".exe" add ".exe" */ exeptr = StrStrI(argv0, ".exe"); if ((exeptr == NULL) || (exeptr != strrchr(argv0, '.'))) { strcat(argv0, ".exe"); dbgprintf(PR_VERBOSE, "%s(): argv0 modified to [%s]/n", __FUNCTION__, argv0); } } return (1);}
开发者ID:oldfaber,项目名称:wzsh,代码行数:88,
示例4: executebool execute(const char* command, std::string currentDir, DWORD& retCode, std::string& output) { HANDLE outWR; SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; TCHAR lpTempPathBuffer[BUFSIZE]; TCHAR szTempFileName[MAX_PATH]; DWORD ret = GetTempPath(BUFSIZE, lpTempPathBuffer); if (ret > BUFSIZE || ret == 0) { MessageBox( NULL, "Error GetTempPath", "Error", MB_OK ); return false; } ret = GetTempFileName(lpTempPathBuffer, "svn", 0, szTempFileName); if (ret == 0) { MessageBox( NULL, "Error GetTempFileName", "Error", MB_OK ); return false; } outWR = CreateFile(szTempFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (outWR == INVALID_HANDLE_VALUE) { MessageBox( NULL, "Error create file", "Error", MB_OK ); return false; } PROCESS_INFORMATION processInfomation; STARTUPINFO startupInfo; memset(&processInfomation, 0, sizeof(processInfomation)); memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); startupInfo.hStdError = outWR; startupInfo.hStdOutput = outWR; startupInfo.dwFlags |= STARTF_USESTDHANDLES; startupInfo.wShowWindow = SW_HIDE; BOOL result = CreateProcess( NULL, (char*) command, NULL, NULL, TRUE, 0, NULL, currentDir.c_str(), &startupInfo, &processInfomation); if (!result) { MessageBox( NULL, "Can't CreateProcess", "Error", MB_OK ); CloseHandle(outWR); return false; } else { WaitForSingleObject(processInfomation.hProcess, INFINITE); GetExitCodeProcess(processInfomation.hProcess, &retCode); CloseHandle(processInfomation.hProcess); CloseHandle(processInfomation.hThread); // read from stdout if (!CloseHandle(outWR)) { MessageBox( NULL, "Can't CloseHandle", "Error", MB_OK ); return false; } outWR = CreateFile(szTempFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (outWR == INVALID_HANDLE_VALUE) { MessageBox( NULL, "Error open file", "Error", MB_OK ); return false; } CHAR buf[BUFSIZE]; DWORD dwRead; DWORD totalSize = 0; std::vector<char*> allBufs; std::vector<DWORD> lens; while (true) { result = ReadFile(outWR, buf, BUFSIZE, &dwRead, NULL); if (!result || dwRead == 0) break; totalSize += dwRead; char* content = new char[dwRead]; memcpy(content, buf, dwRead); allBufs.push_back(content); lens.push_back(dwRead); } char* content = new char[totalSize + 1]; char* currentPtr = content; for (std::size_t i = 0; i < allBufs.size(); i++) { memcpy(currentPtr, allBufs[i], lens[i]); currentPtr += lens[i]; } content[totalSize] = 0; for (std::size_t i = 0; i < allBufs.size(); i++) { delete[] allBufs[i]; } output.swap(std::string(content)); delete[] content; CloseHandle(outWR);//.........这里部分代码省略.........
开发者ID:flexme,项目名称:svnplugin,代码行数:101,
示例5: replace/* makes the replace */INT replace(TCHAR source[MAX_PATH], TCHAR dest[MAX_PATH], DWORD dwFlags, BOOL *doMore){ TCHAR d[MAX_PATH]; TCHAR s[MAX_PATH]; HANDLE hFileSrc, hFileDest; DWORD dwAttrib, dwRead, dwWritten; LPBYTE buffer; BOOL bEof = FALSE; FILETIME srcCreationTime, destCreationTime, srcLastAccessTime, destLastAccessTime; FILETIME srcLastWriteTime, destLastWriteTime; GetPathCase(source, s); GetPathCase(dest, d); s[0] = _totupper(s[0]); d[0] = _totupper(d[0]); // ConOutPrintf(_T("old-src: %s/n"), s); // ConOutPrintf(_T("old-dest: %s/n"), d); // ConOutPrintf(_T("src: %s/n"), source); // ConOutPrintf(_T("dest: %s/n"), dest); /* Open up the sourcefile */ hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,NULL, OPEN_EXISTING, 0, NULL); if (hFileSrc == INVALID_HANDLE_VALUE) { ConOutResPrintf(STRING_COPY_ERROR1, source); return 0; } /* * Get the time from source file to be used in the comparison * with dest time if update switch is set. */ GetFileTime (hFileSrc, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime); /* * Retrieve the source attributes so that they later on * can be inserted in to the destination. */ dwAttrib = GetFileAttributes (source); if (IsExistingFile (dest)) { /* * Resets the attributes to avoid probles with read only files, * checks for read only has been made earlier. */ SetFileAttributes(dest,FILE_ATTRIBUTE_NORMAL); /* * Is the update flas set? The time has to be controled so that * only older files are replaced. */ if (dwFlags & REPLACE_UPDATE) { /* Read destination time */ hFileDest = CreateFile(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFileSrc == INVALID_HANDLE_VALUE) { ConOutResPrintf(STRING_COPY_ERROR1, dest); return 0; } /* Compare time */ GetFileTime (hFileDest, &destCreationTime, &destLastAccessTime, &destLastWriteTime); if (!((srcLastWriteTime.dwHighDateTime > destLastWriteTime.dwHighDateTime) || (srcLastWriteTime.dwHighDateTime == destLastWriteTime.dwHighDateTime && srcLastWriteTime.dwLowDateTime > destLastWriteTime.dwLowDateTime))) { CloseHandle (hFileSrc); CloseHandle (hFileDest); return 0; } CloseHandle (hFileDest); } /* Delete the old file */ DeleteFile (dest); } /* Check confirm flag, and take appropriate action */ if (dwFlags & REPLACE_CONFIRM) { /* Output depending on add flag */ if (dwFlags & REPLACE_ADD) ConOutResPrintf(STRING_REPLACE_HELP9, dest); else ConOutResPrintf(STRING_REPLACE_HELP10, dest); if ( !FilePromptYNA (0)) { CloseHandle (hFileSrc); return 0; } } /* Output depending on add flag */ if (dwFlags & REPLACE_ADD) ConOutResPrintf(STRING_REPLACE_HELP11, dest); else ConOutResPrintf(STRING_REPLACE_HELP5, dest);//.........这里部分代码省略.........
开发者ID:hoangduit,项目名称:reactos,代码行数:101,
示例6: WinMainint WINAPIWinMain ( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ PSTR szCmdLine, _In_ int iCmdShow)/*++Routine Description: Entry point for app. Registers class, creates window.--*/{ CHAR szAppClassName[] = "w1394_AppClass"; CHAR szTitleBar[] = "WDF 1394 Hybrid Test Application"; MSG Msg; WNDCLASSEX WndClassEx; HWND hWnd; UNREFERENCED_PARAMETER (hPrevInstance); UNREFERENCED_PARAMETER (szCmdLine); g_hInstance = hInstance; // main window app... WndClassEx.cbSize = sizeof(WNDCLASSEX); WndClassEx.style = CS_DBLCLKS | CS_BYTEALIGNWINDOW | CS_GLOBALCLASS; WndClassEx.lpfnWndProc = w1394_AppWndProc; WndClassEx.cbClsExtra = 0; WndClassEx.cbWndExtra = 0; WndClassEx.hInstance = g_hInstance; WndClassEx.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); WndClassEx.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); WndClassEx.hCursor = NULL; WndClassEx.hbrBackground = (HBRUSH)COLOR_BACKGROUND; WndClassEx.lpszMenuName = "AppMenu"; WndClassEx.lpszClassName = szAppClassName; RegisterClassEx( &WndClassEx ); hWnd = CreateWindowEx ( WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES, szAppClassName, szTitleBar, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, g_hInstance, NULL); ShowWindow(hWnd, iCmdShow); while (GetMessage(&Msg, NULL, 0, 0)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } if (g_hTestDevice) { CloseHandle (g_hTestDevice); } return (int)(Msg.wParam);} // WinMain
开发者ID:Realhram,项目名称:wdk81,代码行数:71,
示例7: shgfi_get_exe_typestatic DWORD shgfi_get_exe_type(LPCWSTR szFullPath){ BOOL status = FALSE; HANDLE hfile; DWORD BinaryType; IMAGE_DOS_HEADER mz_header; IMAGE_NT_HEADERS nt; DWORD len; char magic[4]; status = GetBinaryTypeW (szFullPath, &BinaryType); if (!status) return 0; if (BinaryType == SCS_DOS_BINARY || BinaryType == SCS_PIF_BINARY) return 0x4d5a; hfile = CreateFileW( szFullPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 ); if ( hfile == INVALID_HANDLE_VALUE ) return 0; /* * The next section is adapted from MODULE_GetBinaryType, as we need * to examine the image header to get OS and version information. We * know from calling GetBinaryTypeA that the image is valid and either * an NE or PE, so much error handling can be omitted. * Seek to the start of the file and read the header information. */ SetFilePointer( hfile, 0, NULL, SEEK_SET ); ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL ); SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ); ReadFile( hfile, magic, sizeof(magic), &len, NULL ); if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE ) { SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ); ReadFile( hfile, &nt, sizeof(nt), &len, NULL ); CloseHandle( hfile ); /* DLL files are not executable and should return 0 */ if (nt.FileHeader.Characteristics & IMAGE_FILE_DLL) return 0; if (nt.OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { return IMAGE_NT_SIGNATURE | (nt.OptionalHeader.MajorSubsystemVersion << 24) | (nt.OptionalHeader.MinorSubsystemVersion << 16); } return IMAGE_NT_SIGNATURE; } else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE ) { IMAGE_OS2_HEADER ne; SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ); ReadFile( hfile, &ne, sizeof(ne), &len, NULL ); CloseHandle( hfile ); if (ne.ne_exetyp == 2) return IMAGE_OS2_SIGNATURE | (ne.ne_expver << 16); return 0; } CloseHandle( hfile ); return 0;}
开发者ID:carlosbislip,项目名称:wine,代码行数:63,
示例8: _tiffCloseProcstatic int_tiffCloseProc(thandle_t fd){ return (CloseHandle(fd) ? 0 : -1);}
开发者ID:etlegacy,项目名称:EasyGen,代码行数:5,
示例9: SFileCreateArchiveEx//.........这里部分代码省略......... nError = ERROR_NOT_ENOUGH_MEMORY; } // Fill the MPQ archive handle structure and create the header, // block buffer, hash table and block table if(nError == ERROR_SUCCESS) { memset(ha, 0, sizeof(TMPQArchive)); strcpy(ha->szFileName, szMpqName); ha->hFile = hFile; ha->dwBlockSize = 0x200 << DEFAULT_BLOCK_SIZE; ha->MpqPos = MpqPos; ha->FilePointer = MpqPos; ha->pHeader = &ha->Header; ha->pHashTable = ALLOCMEM(TMPQHash, dwHashTableSize); ha->pBlockTable = ALLOCMEM(TMPQBlock, dwHashTableSize); ha->pExtBlockTable = ALLOCMEM(TMPQBlockEx, dwHashTableSize); ha->pbBlockBuffer = ALLOCMEM(BYTE, ha->dwBlockSize); ha->pListFile = NULL; ha->dwFlags |= MPQ_FLAG_CHANGED; if(!ha->pHashTable || !ha->pBlockTable || !ha->pExtBlockTable || !ha->pbBlockBuffer) nError = GetLastError(); hFile = INVALID_HANDLE_VALUE; } // Fill the MPQ header and all buffers if(nError == ERROR_SUCCESS) { LARGE_INTEGER TempPos; TMPQHeader2 * pHeader = ha->pHeader; DWORD dwHeaderSize = (wFormatVersion == MPQ_FORMAT_VERSION_2) ? sizeof(TMPQHeader2) : sizeof(TMPQHeader); memset(pHeader, 0, sizeof(TMPQHeader2)); pHeader->dwID = ID_MPQ; pHeader->dwHeaderSize = dwHeaderSize; pHeader->dwArchiveSize = pHeader->dwHeaderSize + dwHashTableSize * sizeof(TMPQHash); pHeader->wFormatVersion = wFormatVersion; pHeader->wBlockSize = 3; // 0x1000 bytes per block pHeader->dwHashTableSize = dwHashTableSize; // Set proper hash table positions ha->HashTablePos.QuadPart = ha->MpqPos.QuadPart + pHeader->dwHeaderSize; ha->pHeader->dwHashTablePos = pHeader->dwHeaderSize; ha->pHeader->wHashTablePosHigh = 0; // Set proper block table positions ha->BlockTablePos.QuadPart = ha->HashTablePos.QuadPart + (ha->pHeader->dwHashTableSize * sizeof(TMPQHash)); TempPos.QuadPart = ha->BlockTablePos.QuadPart - ha->MpqPos.QuadPart; ha->pHeader->dwBlockTablePos = TempPos.LowPart; ha->pHeader->wBlockTablePosHigh = (USHORT)TempPos.HighPart; // For now, we set extended block table positioon top zero unless we add enough // files to cause the archive size exceed 4 GB ha->ExtBlockTablePos.QuadPart = 0; // Clear all tables memset(ha->pBlockTable, 0, sizeof(TMPQBlock) * dwHashTableSize); memset(ha->pExtBlockTable, 0, sizeof(TMPQBlockEx) * dwHashTableSize); memset(ha->pHashTable, 0xFF, sizeof(TMPQHash) * dwHashTableSize); } // Write the MPQ header to the file if(nError == ERROR_SUCCESS) { DWORD dwHeaderSize = ha->pHeader->dwHeaderSize; BSWAP_TMPQHEADER(ha->pHeader); WriteFile(ha->hFile, ha->pHeader, dwHeaderSize, &dwTransferred, NULL); BSWAP_TMPQHEADER(ha->pHeader); if(dwTransferred != ha->pHeader->dwHeaderSize) nError = ERROR_DISK_FULL; ha->FilePointer.QuadPart = ha->MpqPos.QuadPart + dwTransferred; ha->MpqSize.QuadPart += dwTransferred; } // Create the internal listfile if(nError == ERROR_SUCCESS) nError = SListFileCreateListFile(ha); // Try to add the internal listfile if(nError == ERROR_SUCCESS) SFileAddListFile((HANDLE)ha, NULL); // Cleanup : If an error, delete all buffers and return if(nError != ERROR_SUCCESS) { FreeMPQArchive(ha); if(hFile != INVALID_HANDLE_VALUE) CloseHandle(hFile); SetLastError(nError); } // Return the values *phMPQ = (HANDLE)ha; return (nError == ERROR_SUCCESS);}
开发者ID:1ATOM,项目名称:mangos,代码行数:101,
示例10: pipe_read_line/* * The runtime library's popen() on win32 does not work when being * called from a service when running on windows <= 2000, because * there is no stdin/stdout/stderr. * * Executing a command in a pipe and reading the first line from it * is all we need. */static char *pipe_read_line(char *cmd, char *line, int maxsize){#ifndef WIN32 FILE *pgver; /* flush output buffers in case popen does not... */ fflush(stdout); fflush(stderr); errno = 0; if ((pgver = popen(cmd, "r")) == NULL) { perror("popen failure"); return NULL; } errno = 0; if (fgets(line, maxsize, pgver) == NULL) { if (feof(pgver)) fprintf(stderr, "no data was returned by command /"%s/"/n", cmd); else perror("fgets failure"); pclose(pgver); /* no error checking */ return NULL; } if (pclose_check(pgver)) return NULL; return line;#else /* WIN32 */ SECURITY_ATTRIBUTES sattr; HANDLE childstdoutrd, childstdoutwr, childstdoutrddup; PROCESS_INFORMATION pi; STARTUPINFO si; char *retval = NULL; sattr.nLength = sizeof(SECURITY_ATTRIBUTES); sattr.bInheritHandle = TRUE; sattr.lpSecurityDescriptor = NULL; if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0)) return NULL; if (!DuplicateHandle(GetCurrentProcess(), childstdoutrd, GetCurrentProcess(), &childstdoutrddup, 0, FALSE, DUPLICATE_SAME_ACCESS)) { CloseHandle(childstdoutrd); CloseHandle(childstdoutwr); return NULL; } CloseHandle(childstdoutrd); ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdError = childstdoutwr; si.hStdOutput = childstdoutwr; si.hStdInput = INVALID_HANDLE_VALUE; if (CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) { /* Successfully started the process */ char *lineptr; ZeroMemory(line, maxsize); /* Try to read at least one line from the pipe */ /* This may require more than one wait/read attempt */ for (lineptr = line; lineptr < line + maxsize - 1;) {//.........这里部分代码省略.........
开发者ID:42penguins,项目名称:postgres,代码行数:101,
示例11: goodB2GSink/* goodB2G uses the BadSource with the GoodSink */void goodB2GSink(vector<wchar_t *> dataVector){ wchar_t * data = dataVector[2]; { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; char hashData[100] = HASH_INPUT; HCRYPTPROV hCryptProv = 0; HCRYPTHASH hHash = 0; HCRYPTKEY hKey = 0; do { BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */ DWORD payloadBytes; /* Hex-decode the input string into raw bytes */ payloadBytes = decodeHexWChars(payload, sizeof(payload), data); /* Wipe the hex string, to prevent it from being given to LogonUserW if * any of the crypto calls fail. */ SecureZeroMemory(data, 100 * sizeof(wchar_t)); /* Aquire a Context */ if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0)) { break; } /* Create hash handle */ if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash)) { break; } /* Hash the input string */ if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0)) { break; } /* Derive an AES key from the hash */ if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey)) { break; } if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes)) { break; } /* Copy back into data and NUL-terminate */ memcpy(data, payload, payloadBytes); data[payloadBytes / sizeof(wchar_t)] = L'/0'; } while (0); if (hKey) { CryptDestroyKey(hKey); } if (hHash) { CryptDestroyHash(hHash); } if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); } /* FIX: Decrypt the password before using it for authentication */ if (LogonUserW( username, domain, data, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } }}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:80,
示例12: OBSExceptionHandler//.........这里部分代码省略......... fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x/r/n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, frame.AddrPC.Offset)); }#else if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x/r/n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x/r/n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, frame.AddrPC.Offset )); }#endif crashDumpLog.FlushFileBuffers(); } //generate a minidump if possible if (fnMiniDumpWriteDump) { HANDLE hFile; tsprintf_s (dumpPath, _countof(dumpPath)-1, TEXT("%s//crashDumps//OBSCrashDump%.4d-%.2d-%.2d_%d.dmp"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i); hFile = CreateFile (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { miniInfo.ClientPointers = TRUE; miniInfo.ExceptionPointers = exceptionInfo; miniInfo.ThreadId = GetCurrentThreadId (); if (fnMiniDumpWriteDump (hProcess, GetCurrentProcessId(), hFile, MiniDumpWithIndirectlyReferencedMemory, &miniInfo, NULL, NULL)) { crashDumpLog.WriteStr(FormattedString(TEXT("/r/nA minidump was saved to %s./r/nPlease include this file when posting a crash report./r/n"), dumpPath)); } else { CloseHandle (hFile); DeleteFile (dumpPath); } } } else { crashDumpLog.WriteStr(TEXT("/r/nA minidump could not be created. Please check dbghelp.dll is present./r/n")); } crashDumpLog.WriteStr("/r/nList of loaded modules:/r/n");#ifdef _WIN64 crashDumpLog.WriteStr("Base Address Module/r/n");#else crashDumpLog.WriteStr("Base Address Module/r/n");#endif crashDumpLog.WriteStr(strModuleInfo); crashDumpLog.Close(); LocalFree (symInfo); fnSymCleanup (hProcess); if (MessageBox(hwndMain, TEXT("Woops! OBS has crashed. Would you like to view a crash report?"), NULL, MB_ICONERROR | MB_YESNO) == IDYES) ShellExecute(NULL, NULL, logPath, NULL, searchPath, SW_SHOWDEFAULT); FreeLibrary (hDbgHelp); //we really shouldn't be returning here, if we're at the bottom of the VEH chain this is a pretty legitimate crash //and if we return we could end up invoking a second crash handler or other weird / annoying things //ExitProcess(exceptionInfo->ExceptionRecord->ExceptionCode); return EXCEPTION_CONTINUE_SEARCH;}
开发者ID:magicpriest,项目名称:OBS,代码行数:101,
示例13: ReadFromExeFileint ReadFromExeFile(BYTE *filename) {/* Reads data attached to the exe file and calls ProcessData(pointertodata, datasize). Return values: * ERR_READFAILED - read from exe file had failed; * ERR_BADFORMAT - invalid format of the exe file; * ERR_NOINFO - no info was attached. If the data were read OK, it returns the return value of ProcessData.*/ printf("file= %s/n", filename);#define ErrIf(a) if(a) goto HANDLE_BADFORMAT; BYTE buff[4096]; DWORD read; BYTE* data; // Open exe file //GetModuleFileNameA(NULL, (CHAR*)buff, sizeof(buff)); HANDLE hFile = CreateFileA((CHAR*)filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(INVALID_HANDLE_VALUE == hFile) return ERR_READFAILED; if(!ReadFile(hFile, buff, sizeof(buff), &read, NULL)) goto HANDLE_READFAILED; IMAGE_DOS_HEADER* dosheader = (IMAGE_DOS_HEADER*)buff; ErrIf(dosheader->e_magic != IMAGE_DOS_SIGNATURE); ErrIf(ULONG(dosheader->e_lfanew) >= ULONG(sizeof(buff) - sizeof(IMAGE_NT_HEADERS32))); // Locate PE header IMAGE_NT_HEADERS32* header = (IMAGE_NT_HEADERS32*)(buff + dosheader->e_lfanew); ErrIf(header->Signature != IMAGE_NT_SIGNATURE); IMAGE_SECTION_HEADER* sectiontable = (IMAGE_SECTION_HEADER*)((BYTE*)header + sizeof(IMAGE_NT_HEADERS32)); ErrIf((BYTE*)sectiontable >= buff + sizeof(buff)); DWORD maxpointer = 0, exesize = 0; // For each section for(int i = 0; i < header->FileHeader.NumberOfSections; ++i) { if(sectiontable->PointerToRawData > maxpointer) { maxpointer = sectiontable->PointerToRawData; exesize = sectiontable->PointerToRawData + sectiontable->SizeOfRawData; } sectiontable++; } // Seek to the overlay DWORD filesize = GetFileSize(hFile, NULL); if(exesize == filesize) goto HANDLE_NOINFO; ErrIf(filesize == INVALID_FILE_SIZE || exesize > filesize); if(SetFilePointer(hFile, exesize, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) goto HANDLE_READFAILED; data = (BYTE*)malloc(filesize - exesize + 8); if(!ReadFile(hFile, data, filesize - exesize, &read, NULL)) goto HANDLE_WITHFREE; CloseHandle(hFile); // Process the data int result = ProcessData(data, filesize - exesize); free(data); return result;HANDLE_WITHFREE: free(data);HANDLE_READFAILED: CloseHandle(hFile); return ERR_READFAILED;HANDLE_BADFORMAT: CloseHandle(hFile); return ERR_BADFORMAT;HANDLE_NOINFO: CloseHandle(hFile); return ERR_NOINFO;#undef ErrIf}
开发者ID:hidd3ncod3s,项目名称:dumpoverlay,代码行数:69,
示例14: CreateFileWvoid starnt::dictionary::load(const std::wstring file){ if( !dict.empty()) if(file == dict_file) return; else dict.clear(); char* word; [&file, &word]()->void { #if defined _WIN32 HANDLE FileIn; FileIn = CreateFileW( file.c_str(),GENERIC_READ ,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL); if (FileIn == INVALID_HANDLE_VALUE) return; LARGE_INTEGER len; GetFileSizeEx(FileIn, &len); word = new char[len.LowPart + 1]; DWORD count; ReadFile(FileIn, word, len.LowPart, &count, NULL); if(count != len.LowPart) return; word[len.LowPart] = '/0'; CloseHandle(FileIn); #else // nix version #endif }(); //load individual words into strings std::pair<std::string, std::string> dict_entry; char* wordtok; wordtok = strtok(word, "/n"); for(int j = 0 ; wordtok != NULL ; j++ , wordtok = strtok(NULL, "/n")) { if(type == 1) { // encode dict_entry.first = wordtok; // the word transform(j, dict_entry.second); // code } else { //decode transform(j, dict_entry.first); // code dict_entry.second = wordtok; // the word } dict.insert( dict_entry ); } // replace LF with /0/* for(size_t i=0; i < len ; i++) { while( (word[i] != '/n') && i < len) i++; word[i] = '/0'; } // then load individual words into strings std::pair<std::string, std::string> dict_entry; dict_entry.first= &word[0]; dict_entry.second = "a"; dict.insert( dict_entry ); for(int i = 2, j = 1 ; i < len ; i++,j++) { while(word[i] != '/0') i++; i++; if( i <len) { dict_entry.first = &word[i]; // the word dict_entry.second = transform(j); // code dict.insert( dict_entry ); } else break; }*/ delete [] word;}
开发者ID:ksteinhaeuser,项目名称:starnt,代码行数:87,
示例15: main//.........这里部分代码省略.........#ifndef __MINGW32__ flv = mmap(NULL, filesize, PROT_READ, MAP_NOCORE | MAP_PRIVATE, fileno(fp_infile), 0); if(flv == MAP_FAILED) { fprintf(stderr, "Couldn't load %s (%s)./n", infile, strerror(errno)); exit(1); }#else HANDLE h = NULL; h = CreateFileMapping(fh_infile, NULL, PAGE_READONLY | SEC_COMMIT, 0, filesize, NULL); if(h == NULL) { fprintf(stderr, "Couldn't create file mapping object %s. Error code: %d/n", infile, (int)GetLastError()); exit(1); } flv = MapViewOfFile(h, FILE_MAP_READ, 0, 0, filesize); if(flv == NULL) { fprintf(stderr, "Couldn't load %s./n", infile); exit(1); }#endif // Simple check if the filee is a flv file if(strncmp(flv, "FLV", 3)) { fprintf(stderr, "The input file is not a FLV./n"); exit(1); } // Metadata initialisieren initFLVMetaData(creator, lastsecond, lastkeyframe); flvfileheader = (FLVFileHeader_t *)flv; // Die Position des 1. Tags im FLV bestimmen (Header + PrevTagSize0) streampos = FLV_UI32(flvfileheader->headersize) + 4; // Das FLV einlesen und Informationen fuer die Metatags extrahieren readFLVFirstPass(flv, streampos, filesize);#ifndef __MINGW32__ devnull = fopen("/dev/null", "wb");#else devnull = fopen("nul", "wb");#endif if(devnull == NULL) { fprintf(stderr, "Couldn't open NULL device./n"); exit(1); } // Die Groessen berechnen metadatasize = writeFLVMetaData(devnull); flvmetadata.lastsecondsize = writeFLVLastSecond(devnull, 0.0); flvmetadata.lastkeyframesize = writeFLVLastKeyframe(devnull); // Not fully implemented, i.e. has no effect fclose(devnull); // Falls es Keyframes hat, muss ein 2. Durchgang fuer den Keyframeindex gemacht werden if(flvmetadata.hasKeyframes == 1) { readFLVSecondPass(flv, streampos, filesize); // Die Filepositions korrigieren for(i = 0; i < flvmetadata.keyframes; i++) flvmetadata.filepositions[i] += (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize); flvmetadata.lastkeyframelocation = flvmetadata.filepositions[flvmetadata.keyframes - 1]; } // filesize = FLVFileHeader + PreviousTagSize0 + MetadataSize + DataSize flvmetadata.filesize = (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize + flvmetadata.datasize); if(flvmetadata.hasLastSecond == 1) flvmetadata.filesize += (double)flvmetadata.lastsecondsize; if(outfile != NULL) writeFLV(fp_outfile, flv, streampos, filesize); if(xmloutfile != NULL) writeXMLMetadata(fp_xmloutfile, infile, outfile); // Some cleanup#ifndef __MINGW32__ munmap(flv, filesize); fclose(fp_infile);#else UnmapViewOfFile(flv); CloseHandle(h); CloseHandle(fh_infile);#endif // Remove the input file if it is the temporary file if(unlink_infile == 1) unlink(infile); if(fp_outfile != NULL && fp_outfile != stdout) fclose(fp_outfile); if(fp_xmloutfile != NULL && fp_xmloutfile != stdout) fclose(fp_xmloutfile); return 0;}
开发者ID:danielbush,项目名称:fez,代码行数:101,
示例16: CloseHandle ~Implementation() { CloseHandle( breakEvent_ ); }
开发者ID:AlexBobkov,项目名称:OpenSceneGraph,代码行数:4,
示例17: EncryptionThreadPoolStartBOOL EncryptionThreadPoolStart (){ size_t cpuCount, i; if (ThreadPoolRunning) return TRUE;#ifdef DEVICE_DRIVER cpuCount = GetCpuCount();#else { SYSTEM_INFO sysInfo; GetSystemInfo (&sysInfo); cpuCount = sysInfo.dwNumberOfProcessors; }#endif if (cpuCount < 2) return TRUE; if (cpuCount > TC_ENC_THREAD_POOL_MAX_THREAD_COUNT) cpuCount = TC_ENC_THREAD_POOL_MAX_THREAD_COUNT; StopPending = FALSE; DequeuePosition = 0; EnqueuePosition = 0;#ifdef DEVICE_DRIVER KeInitializeEvent (&WorkItemReadyEvent, SynchronizationEvent, FALSE); KeInitializeEvent (&WorkItemCompletedEvent, SynchronizationEvent, FALSE);#else WorkItemReadyEvent = CreateEvent (NULL, FALSE, FALSE, NULL); if (!WorkItemReadyEvent) return FALSE; WorkItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); if (!WorkItemCompletedEvent) { CloseHandle (WorkItemReadyEvent); return FALSE; }#endif TC_INIT_MUTEX (&DequeueMutex); TC_INIT_MUTEX (&EnqueueMutex); memset (WorkItemQueue, 0, sizeof (WorkItemQueue)); for (i = 0; i < sizeof (WorkItemQueue) / sizeof (WorkItemQueue[0]); ++i) { WorkItemQueue[i].State = WorkItemFree;#ifdef DEVICE_DRIVER KeInitializeEvent (&WorkItemQueue[i].ItemCompletedEvent, SynchronizationEvent, FALSE);#else WorkItemQueue[i].ItemCompletedEvent = CreateEvent (NULL, FALSE, FALSE, NULL); if (!WorkItemQueue[i].ItemCompletedEvent) { EncryptionThreadPoolStop(); return FALSE; }#endif } for (ThreadCount = 0; ThreadCount < cpuCount; ++ThreadCount) {#ifdef DEVICE_DRIVER if (!NT_SUCCESS (TCStartThread (EncryptionThreadProc, NULL, &ThreadHandles[ThreadCount])))#else if (!(ThreadHandles[ThreadCount] = (HANDLE) _beginthreadex (NULL, 0, EncryptionThreadProc, NULL, 0, NULL)))#endif { EncryptionThreadPoolStop(); return FALSE; } } ThreadPoolRunning = TRUE; return TRUE;}
开发者ID:shimbongsu,项目名称:secure-share-fss,代码行数:80,
示例18: Run void Run() { break_ = false; // prepare the window events which we use to wake up on incoming data // we use this instead of select() primarily to support the AsyncBreak() // mechanism. std::vector<HANDLE> events( socketListeners_.size() + 1, 0 ); int j=0; for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); i != socketListeners_.end(); ++i, ++j ){ HANDLE event = CreateEvent( NULL, FALSE, FALSE, NULL ); WSAEventSelect( i->second->impl_->Socket(), event, FD_READ ); // note that this makes the socket non-blocking which is why we can safely call RecieveFrom() on all sockets below events[j] = event; } events[ socketListeners_.size() ] = breakEvent_; // last event in the collection is the break event // configure the timer queue double currentTimeMs = GetCurrentTimeMs(); // expiry time ms, listener std::vector< std::pair< double, AttachedTimerListener > > timerQueue_; for( std::vector< AttachedTimerListener >::iterator i = timerListeners_.begin(); i != timerListeners_.end(); ++i ) timerQueue_.push_back( std::make_pair( currentTimeMs + i->initialDelayMs, *i ) ); std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); const int MAX_BUFFER_SIZE = 4098; char *data = new char[ MAX_BUFFER_SIZE ]; IpEndpointName remoteEndpoint; while( !break_ ){ currentTimeMs = GetCurrentTimeMs(); DWORD waitTime = INFINITE; if( !timerQueue_.empty() ){ waitTime = (DWORD)( timerQueue_.front().first >= currentTimeMs ? timerQueue_.front().first - currentTimeMs : 0 ); } DWORD waitResult = WaitForMultipleObjects( (DWORD)socketListeners_.size() + 1, &events[0], FALSE, waitTime ); if( break_ ) break; if( waitResult != WAIT_TIMEOUT ){ for( int i = waitResult - WAIT_OBJECT_0; i < (int)socketListeners_.size(); ++i ){ int size = socketListeners_[i].second->ReceiveFrom( remoteEndpoint, data, MAX_BUFFER_SIZE ); if( size > 0 ){ socketListeners_[i].first->ProcessPacket( data, size, remoteEndpoint ); if( break_ ) break; } } } // execute any expired timers currentTimeMs = GetCurrentTimeMs(); bool resort = false; for( std::vector< std::pair< double, AttachedTimerListener > >::iterator i = timerQueue_.begin(); i != timerQueue_.end() && i->first <= currentTimeMs; ++i ){ i->second.listener->TimerExpired(); if( break_ ) break; i->first += i->second.periodMs; resort = true; } if( resort ) std::sort( timerQueue_.begin(), timerQueue_.end(), CompareScheduledTimerCalls ); } delete [] data; // free events j = 0; for( std::vector< std::pair< PacketListener*, UdpSocket* > >::iterator i = socketListeners_.begin(); i != socketListeners_.end(); ++i, ++j ){ WSAEventSelect( i->second->impl_->Socket(), events[j], 0 ); // remove association between socket and event CloseHandle( events[j] ); unsigned long enableNonblocking = 0; ioctlsocket( i->second->impl_->Socket(), FIONBIO, &enableNonblocking ); // make the socket blocking again } }
开发者ID:AlexBobkov,项目名称:OpenSceneGraph,代码行数:93,
示例19: proc_title_setvoidproc_title_set(const char *format, ...){#ifndef PS_USE_NONE va_list ap; int buflen;#ifdef PS_USE_CLOBBER_ARGV /* If ps_buffer is a pointer, it might still be null */ if (!ps_buffer) return;#endif /* Update ps_buffer to contain both fixed part and activity */ va_start(ap, format); buflen = vsnprintf(ps_buffer, ps_buffer_size - ps_sentinel_size, format, ap); va_end(ap); if (buflen < 0) return; /* Transmit new setting to kernel, if necessary */#ifdef PS_USE_SETPROCTITLE setproctitle("-%s", ps_buffer);#endif#ifdef PS_USE_PSTAT { union pstun pst; pst.pst_command = ps_buffer; pstat(PSTAT_SETCMD, pst, strlen(ps_buffer), 0, 0); }#endif /* PS_USE_PSTAT */#ifdef PS_USE_PS_STRINGS static char *argvstr[2]; argvstr[0] = ps_buffer; PS_STRINGS->ps_nargvstr = 1; PS_STRINGS->ps_argvstr = argvstr;#endif /* PS_USE_PS_STRINGS */#ifdef PS_USE_CLOBBER_ARGV { /* clobber remainder of old status string */ if (ps_last_status_len > (size_t)buflen) memset(ps_buffer + buflen, PS_PADDING, ps_last_status_len - buflen); ps_last_status_len = buflen; }#endif /* PS_USE_CLOBBER_ARGV */#ifdef PS_USE_WIN32 { /* * Win32 does not support showing any changed arguments. To make it at * all possible to track which backend is doing what, we create a * named object that can be viewed with for example Process Explorer. */ static HANDLE ident_handle = INVALID_HANDLE_VALUE; char name[PS_BUFFER_SIZE + 32]; if (ident_handle != INVALID_HANDLE_VALUE) CloseHandle(ident_handle); sprintf(name, "pgident(%d): %s", MyProcPid, ps_buffer); ident_handle = CreateEvent(NULL, TRUE, FALSE, name); }#endif /* PS_USE_WIN32 */#endif /* not PS_USE_NONE */}
开发者ID:marvin-h,项目名称:tarantool,代码行数:72,
示例20: ExpandEnvironmentStringsWvoid CPutFile::CheckExe(wstring installname, wstring name, int type){ if(type == 2)//file { WCHAR path[MAX_PATH] = {0}; ExpandEnvironmentStringsW(installname.c_str(), path, MAX_PATH); if(::PathFileExistsW(path) == TRUE) return; } else if(type == 1)//reg { HKEY rootkey; size_t nEndKeyName = installname.find_first_of(']', 1); std::wstring strKeyName = installname.substr(1, nEndKeyName - 1); size_t nEnd = strKeyName.find_first_of('//'); std::wstring strRootKey = strKeyName.substr(0, nEnd); if(strRootKey == L"HKEY_CURRENT_USER") rootkey = HKEY_CURRENT_USER; else if (strRootKey == _T("HKEY_LOCAL_MACHINE")) rootkey = HKEY_LOCAL_MACHINE; else if(strRootKey == _T("HKEY_CLASSES_ROOT")) rootkey = HKEY_CLASSES_ROOT; std::wstring strKey = strKeyName.substr(nEnd + 1, wstring::npos); HKEY hKey = NULL; // 操作键句柄 if (ERROR_SUCCESS == ::RegOpenKeyExW(rootkey, strKey.c_str(), 0, KEY_READ, &hKey)) { ::RegCloseKey(hKey); return; } } else return; wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str()); OSVERSIONINFO os = { sizeof(OSVERSIONINFO) }; ::GetVersionEx(&os); if(os.dwMajorVersion >= 6) { SHELLEXECUTEINFOW shExecInfo; shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO); shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;//SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI; shExecInfo.hwnd = NULL; shExecInfo.lpVerb = L"runas"; shExecInfo.lpFile = LPWSTR(file.c_str()); shExecInfo.lpParameters = NULL; shExecInfo.lpDirectory = NULL; shExecInfo.nShow = SW_SHOWNORMAL; shExecInfo.hInstApp = NULL; if (!ShellExecuteExW(&shExecInfo)) { int err = GetLastError(); CRecordProgram::GetInstance()->FeedbackError(L"PutFile", err, CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str())); } else WaitForSingleObject (shExecInfo.hProcess, INFINITE); } else { STARTUPINFOW si; memset (&si, 0, sizeof (STARTUPINFOW)); si.wShowWindow = SW_HIDE; si.cb = sizeof (STARTUPINFOW); PROCESS_INFORMATION pi; memset (&pi, 0, sizeof (PROCESS_INFORMATION)); if (!CreateProcess(NULL, LPWSTR(file.c_str()), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { CRecordProgram::GetInstance()->FeedbackError(L"PutFile", 1200, CRecordProgram::GetInstance()->GetRecordInfo(L"CPutFile创建安装进程%s失败!", file.c_str())); return; } else WaitForSingleObject (pi.hProcess, INFINITE); CloseHandle (pi.hThread); CloseHandle (pi.hProcess); } return;}
开发者ID:Williamzuckerberg,项目名称:chtmoneyhub,代码行数:87,
示例21: rpl_stat//.........这里部分代码省略......... - by opening the file directly. The first approach fails for root directories (e.g. 'C:/') and UNC root directories (e.g. '//server/share'). The second approach fails for some system files (e.g. 'C:/pagefile.sys' and 'C:/hiberfil.sys'): ERROR_SHARING_VIOLATION. The second approach gives more information (in particular, correct st_dev, st_ino, st_nlink fields). So we use the second approach and, as a fallback except for root and UNC root directories, also the first approach. */ { int ret; { /* Approach based on the file. */ /* Open a handle to the file. CreateFile <https://msdn.microsoft.com/en-us/library/aa363858.aspx> <https://msdn.microsoft.com/en-us/library/aa363874.aspx> */ HANDLE h = CreateFile (rname, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, /* FILE_FLAG_POSIX_SEMANTICS (treat file names that differ only in case as different) makes sense only when applied to *all* filesystem operations. */ FILE_FLAG_BACKUP_SEMANTICS /* | FILE_FLAG_POSIX_SEMANTICS */, NULL); if (h != INVALID_HANDLE_VALUE) { ret = _gl_fstat_by_handle (h, rname, buf); CloseHandle (h); goto done; } } /* Test for root and UNC root directories. */ if ((rlen == drive_prefix_len + 1 && ISSLASH (rname[drive_prefix_len])) || is_unc_root (rname)) goto failed; /* Fallback. */ { /* Approach based on the directory entry. */ if (strchr (rname, '?') != NULL || strchr (rname, '*') != NULL) { /* Other Windows API functions would fail with error ERROR_INVALID_NAME. */ if (malloca_rname != NULL) freea (malloca_rname); errno = ENOENT; return -1; } /* Get the details about the directory entry. This can be done through FindFirstFile <https://msdn.microsoft.com/en-us/library/aa364418.aspx> <https://msdn.microsoft.com/en-us/library/aa365740.aspx> or through FindFirstFileEx with argument FindExInfoBasic <https://msdn.microsoft.com/en-us/library/aa364419.aspx> <https://msdn.microsoft.com/en-us/library/aa364415.aspx> <https://msdn.microsoft.com/en-us/library/aa365740.aspx> */
开发者ID:Linkerist,项目名称:lide,代码行数:67,
示例22: pWow64DisableWow64FsRedirectionvoid CPutFile::CheckFile(wstring name, wstring path, bool replace){ HMODULE hKernel32 = ::LoadLibrary(_T("Kernel32.dll")); PVOID OldValue; BOOL bRet = FALSE; if(CGetOSInfo::getInstance()->isX64()) { Wow64DisableWow64FsRedirectionFun pWow64DisableWow64FsRedirection = NULL; if (hKernel32) { pWow64DisableWow64FsRedirection = (Wow64DisableWow64FsRedirectionFun)::GetProcAddress(hKernel32, "Wow64DisableWow64FsRedirection"); } if(pWow64DisableWow64FsRedirection != NULL) bRet = pWow64DisableWow64FsRedirection(&OldValue); } wstring fullPath; fullPath = path + L"//" + name; WCHAR expName[MAX_PATH] ={0}; ExpandEnvironmentStringsW(fullPath.c_str(), expName, MAX_PATH); if(::PathFileExistsW(expName) == FALSE)// 判断文件是否存在 { CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"%s文件不存在", expName)); wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str()); ::CopyFileW(file.c_str(), expName , TRUE); DWORD re = ::GetLastError(); CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"替换%s文件结果:%d", file.c_str(),re)); if(re == ERROR_ACCESS_DENIED) { CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"%s文件放入失败", file.c_str())); USES_CONVERSION; string appid; if(m_pWebsiteData) { USES_CONVERSION; appid = CFavBankOperator::GetBankIDOrBankName(W2A(m_pWebsiteData->GetID()),false); CWebsiteData::StartUAC(A2W(appid.c_str())); } } } else { if(replace == true)//强制替换 { DWORD oLength = 0, nLength = 0; HANDLE hFile = CreateFileW(expName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile != INVALID_HANDLE_VALUE) { oLength = GetFileSize(hFile, NULL); CloseHandle(hFile); } CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"%s文件已经存在", expName)); wstring file = CResourceManager::_()->GetFilePath(m_pWebsiteData->GetWebsiteType(), m_pWebsiteData->GetID(), name.c_str()); hFile = CreateFileW(file.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile != INVALID_HANDLE_VALUE) { nLength = GetFileSize(hFile, NULL); CloseHandle(hFile); } if((oLength != 0) && (oLength != nLength)) { ::CopyFileW(file.c_str(), expName , FALSE);// DWORD re = ::GetLastError(); CRecordProgram::GetInstance ()->RecordCommonInfo(L"PutFile", 1001, CRecordProgram::GetInstance ()->GetRecordInfo(L"替换%s文件结果:%d", file.c_str(),re)); if(re == ERROR_ACCESS_DENIED) { USES_CONVERSION; string appid; if(m_pWebsiteData) { appid = CFavBankOperator::GetBankIDOrBankName(W2A(m_pWebsiteData->GetID()),false); CWebsiteData::StartUAC(A2W(appid.c_str())); } } } } } if(CGetOSInfo::getInstance()->isX64()) if(bRet == TRUE) { Wow64RevertWow64FsRedirectionFun pWow64RevertWow64FsRedirection = NULL; if (hKernel32) { pWow64RevertWow64FsRedirection = (Wow64RevertWow64FsRedirectionFun)::GetProcAddress(hKernel32, "Wow64RevertWow64FsRedirection"); } if(pWow64RevertWow64FsRedirection != NULL) pWow64RevertWow64FsRedirection(OldValue); } return;}
开发者ID:Williamzuckerberg,项目名称:chtmoneyhub,代码行数:98,
示例23: WinMainint WINAPI WinMain(HINSTANCE hInstance, // handle to current instance HINSTANCE hPrevInstance, // handle to previous instance LPWSTR lpCmdLine, // pointer to command line int nCmdShow) // show state of window{ HANDLE tRx, tTx; BOOL dma_enable = FALSE; NKDbgPrintfW(L"******************************************/n/r"); NKDbgPrintfW(L"********* Program Start **************/n/r"); NKDbgPrintfW(L"******************************************/n/r"); dma_enable = FALSE; bufferTx = sbufferTx; bufferRx = sbufferRx; if ((bufferRx == NULL) || (bufferTx == NULL)) { printf("Could not alloc buffers"); return FALSE; } //Initialize SSP1 (Master) //----------------------------- if (!SPIInit(txSSPport, DATABITS, SPI_CLOCK_812_KHZ, SPI_MASTER, SPI_MODE_3, NULL)) { printf("Error in InitSPI"); return FALSE; } //Initialize SSP2 (Slave) //----------------------------- if (!SPIInit(rxSSPport, DATABITS, SPI_CLOCK_812_KHZ, SPI_SLAVE, SPI_MODE_3, NULL)) { printf("Error in InitSPI"); return FALSE; } //Create and start transmit/receive threads //----------------------------- tRx = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) RXThread, 0, 0, NULL); CeSetThreadPriority(tRx,10); //Set receive thread to a high priority to avoid buffer overflows //Sleep(100); tTx = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) TXThread, 0, 0, NULL); printf("/r/nPress ENTER to leave the application./r/n"); getchar(); TerminateThread(tRx, 0); TerminateThread(tTx, 0); Sleep(20); CloseHandle(tRx); CloseHandle(tTx); //Deinit //Very Important //if you forget to Deinit a SPI and Init the SPI new the spi interrupts will not work. //In this case you have to reset the System DeinitSPI(txSSPport); DeinitSPI(rxSSPport); return TRUE;}
开发者ID:kleberandrade,项目名称:robot-rehab-system,代码行数:68,
示例24: memsetBOOL Osmo4::InitInstance(){ CCommandLineInfo cmdInfo; m_logs = NULL; m_term = NULL; memset(&m_user, 0, sizeof(GF_User)); /*get Osmo4.exe path*/ strcpy((char *) szApplicationPath, AfxGetApp()->m_pszHelpFilePath); while (szApplicationPath[strlen((char *) szApplicationPath)-1] != '//') szApplicationPath[strlen((char *) szApplicationPath)-1] = 0; if (szApplicationPath[strlen((char *) szApplicationPath)-1] != '//') strcat(szApplicationPath, "//"); gf_sys_init(0); /*setup user*/ memset(&m_user, 0, sizeof(GF_User)); Bool first_launch = 0; /*init config and modules*/ m_user.config = gf_cfg_init(NULL, &first_launch); if (!m_user.config) { MessageBox(NULL, "GPAC Configuration file not found", "Fatal Error", MB_OK); m_pMainWnd->PostMessage(WM_CLOSE); } char *name = gf_cfg_get_filename(m_user.config); char *sep = strrchr(name, '//'); if (sep) sep[0] = 0; strcpy(szUserPath, name); if (sep) sep[0] = '//'; gf_free(name); const char *opt = gf_cfg_get_key(m_user.config, "General", "SingleInstance"); m_SingleInstance = (opt && !stricmp(opt, "yes")) ? 1 : 0; m_hMutex = NULL; if (m_SingleInstance) { m_hMutex = CreateMutex(NULL, FALSE, "Osmo4_GPAC_INSTANCE"); if ( GetLastError() == ERROR_ALREADY_EXISTS ) { char szDIR[1024]; if (m_hMutex) CloseHandle(m_hMutex); m_hMutex = NULL; if (!static_gpac_hwnd || !IsWindow(static_gpac_hwnd) ) { ::MessageBox(NULL, "Osmo4 ghost process detected", "Error at last shutdown" , MB_OK); } else { ::SetForegroundWindow(static_gpac_hwnd); if (m_lpCmdLine && strlen(m_lpCmdLine)) { DWORD res; u32 len; char *the_url, *cmd; GetCurrentDirectory(1024, szDIR); if (szDIR[strlen(szDIR)-1] != '//') strcat(szDIR, "//"); cmd = (char *)(const char *) m_lpCmdLine; strcpy(static_szCmdLine, ""); if (cmd[0]=='"') cmd+=1; if (!strnicmp(cmd, "-queue ", 7)) { strcat(static_szCmdLine, "-queue "); cmd += 7; } the_url = gf_url_concatenate(szDIR, cmd); if (!the_url) { strcat(static_szCmdLine, cmd); } else { strcat(static_szCmdLine, the_url); gf_free(the_url); } while ( (len = strlen(static_szCmdLine)) ) { char s = static_szCmdLine[len-1]; if ((s==' ') || (s=='"')) static_szCmdLine[len-1]=0; else break; } ::SendMessageTimeout(static_gpac_hwnd, WM_NEWINSTANCE, 0, 0, 0, 1000, &res); } } return FALSE; } }#if 0 // Standard initialization#ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL#else Enable3dControlsStatic(); // Call this when linking to MFC statically#endif#endif SetRegistryKey(_T("GPAC")); CMainFrame* pFrame = new CMainFrame; m_pMainWnd = pFrame; pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL); m_pMainWnd->DragAcceptFiles();//.........这里部分代码省略.........
开发者ID:casperploug,项目名称:gpac,代码行数:101,
示例25: try_shell_exstatic int try_shell_ex(char *argv0, const char *const *argv, unsigned long shellexflags, char **cmdstr, unsigned int *cmdsize){ char *cmdend; size_t cmdlen; SHELLEXECUTEINFO shinfo; BOOL nocmd = 0; path_to_backslash(argv0); /* @@@@ is this code really needed ? when ? */ if ((!*argv) && (argv0[0] == '//') && (argv0[1] == '//')) { shellexflags |= SEE_MASK_CONNECTNETDRV; nocmd = 1; goto noargs; } cmdend = *cmdstr; cmdlen = 0; concat_args_and_quote(argv, cmdstr, &cmdlen, &cmdend, cmdsize); *cmdend = '/0';noargs: dbgprintf(PR_EXEC, "ShellExecute(%s, ..) with cmdstr [%s]/n", argv0, *cmdstr); memset(&shinfo, 0, sizeof(shinfo)); shinfo.cbSize = sizeof(shinfo); shinfo.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_FLAG_DDEWAIT | shellexflags; shinfo.hwnd = NULL; shinfo.lpVerb = NULL; shinfo.lpFile = argv0; shinfo.lpParameters = nocmd ? NULL : *cmdstr; shinfo.lpDirectory = 0; shinfo.nShow = SW_SHOWDEFAULT; if (ShellExecuteEx(&shinfo)) { DWORD retval = 255; dbgprintf(PR_EXEC, "ShellExecute() created process handle 0x%p/n", shinfo.hProcess); /* may happen if "executing" a file associated to a running program, i.e. "execute" a .html file with an already opened browser window */ if (shinfo.hProcess != (HANDLE)0) { if (shellexflags & SEE_MASK_NOCLOSEPROCESS) { if ((intptr_t)(shinfo.hInstApp) > 32) { if (WaitForSingleObject(shinfo.hProcess, INFINITE) == WAIT_OBJECT_0) { /* try to get the return value */ GetExitCodeProcess(shinfo.hProcess, &retval); } else { dbgprintf(PR_ERROR, "!!! ShellExecute() [%s] WaitForSingleObject() error %ld/n", argv0, GetLastError()); } } else { dbgprintf(PR_ERROR, "!!! ShellExecute() [%s] error %p/n", argv0, shinfo.hInstApp); } } /* try to close, it may fail but .. what else could we do */ CloseHandle(shinfo.hProcess); } dbgprintf(PR_ALL, "--- %s(): ShellExecute() OK, exiting with code %ld/n", __FUNCTION__, retval); exec_exit((int)retval); } else { dbgprintf(PR_EXEC, "ShellExecute() failed/n"); } return (0);}
开发者ID:oldfaber,项目名称:wzsh,代码行数:61,
示例26: ProcessExceptionLONG ProcessException(struct _EXCEPTION_POINTERS *ExceptionInfo){ char appDescriptor[_MAX_PATH]; if ((CrashReporter::controls.actionToTake & AOC_SILENT_MODE) == 0) { sprintf(appDescriptor, "%s has crashed./nGenerate a report?", CrashReporter::controls.appName); if (::MessageBox( NULL, appDescriptor, "Crash Reporter", MB_YESNO )==IDNO) { return EXCEPTION_CONTINUE_SEARCH; } } char dumpFilepath[_MAX_PATH]; char dumpFilename[_MAX_PATH]; sprintf(appDescriptor, "%s %s - %s %s", CrashReporter::controls.appName, CrashReporter::controls.appVersion, __DATE__, __TIME__); if ((CrashReporter::controls.actionToTake & AOC_EMAIL_WITH_ATTACHMENT) || (CrashReporter::controls.actionToTake & AOC_WRITE_TO_DISK) ) { if (CrashReporter::controls.actionToTake & AOC_WRITE_TO_DISK) { strcpy(dumpFilepath, CrashReporter::controls.pathToMinidump); WriteFileWithDirectories(dumpFilepath,0,0); AddSlash(dumpFilepath); } else { // Write to a temporary directory if the user doesn't want the dump on the harddrive. if (!GetTempPath( _MAX_PATH, dumpFilepath )) dumpFilepath[0]=0; } unsigned i, dumpFilenameLen; strcpy(dumpFilename, appDescriptor); dumpFilenameLen=(unsigned) strlen(appDescriptor); for (i=0; i < dumpFilenameLen; i++) if (dumpFilename[i]==':' || dumpFilename[i]=='/' || dumpFilename[i]=='//') dumpFilename[i]='.'; // Remove illegal characters from filename strcat(dumpFilepath, dumpFilename); strcat(dumpFilepath, ".dmp"); HANDLE hFile = CreateFile(dumpFilepath,GENERIC_WRITE, FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); if (hFile==INVALID_HANDLE_VALUE) return EXCEPTION_CONTINUE_SEARCH; MINIDUMP_EXCEPTION_INFORMATION eInfo; eInfo.ThreadId = GetCurrentThreadId(); eInfo.ExceptionPointers = ExceptionInfo; eInfo.ClientPointers = FALSE; if (MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, (MINIDUMP_TYPE)CrashReporter::controls.minidumpType, ExceptionInfo ? &eInfo : NULL, NULL, NULL)==false) return EXCEPTION_CONTINUE_SEARCH; CloseHandle(hFile); } char silentModeEmailBody[1024]; char subject[1204]; if (CrashReporter::controls.actionToTake & AOC_EMAIL_NO_ATTACHMENT) { strcpy(subject, CrashReporter::controls.emailSubjectPrefix); strcat(subject, appDescriptor); if (CrashReporter::controls.actionToTake & AOC_SILENT_MODE) { sprintf(silentModeEmailBody, "%s version %s has crashed./r/nIt was compiled on %s %s./r/n", CrashReporter::controls.appName,CrashReporter::controls.appVersion, __DATE__, __TIME__); if (CrashReporter::controls.actionToTake & AOC_WRITE_TO_DISK) sprintf(silentModeEmailBody+strlen(silentModeEmailBody), "Minidump written to %s /r/n", dumpFilepath); // Silently send email with attachment EmailSender emailSender; emailSender.Send(CrashReporter::controls.SMTPServer, 25, CrashReporter::controls.SMTPAccountName, CrashReporter::controls.emailRecipient, CrashReporter::controls.emailSender, CrashReporter::controls.emailRecipient, subject, silentModeEmailBody, 0, false, CrashReporter::controls.emailPassword); } else { CSendFileTo sendFile; sendFile.SendMail(0, 0, 0, subject, CrashReporter::controls.emailBody, CrashReporter::controls.emailRecipient); } } else if (CrashReporter::controls.actionToTake & AOC_EMAIL_WITH_ATTACHMENT) { strcpy(subject, CrashReporter::controls.emailSubjectPrefix);//.........这里部分代码省略.........
开发者ID:Caboose1543,项目名称:LUNIServerProject,代码行数:101,
示例27: nt_execve//.........这里部分代码省略......... shflags = SEE_MASK_NO_CONSOLE | SEE_MASK_NOCLOSEPROCESS; if (try_shell_ex(argv0, args, shflags, &cmdstr, &cmdsize)) return (0); /* ShellExecute failed, the file has an unknown extension, but it may be a shell script with a shebang */ if (process_shebang(argv0, (const char *const *)&cmdstr, &cmdlen, &cmdend, &cmdsize) > 0) { cmdend = cmdstr + cmdlen; execmode = directex; } else { /* the file extension is NOT known and the file has NO shebang: returns EPERM, see NOTES */ errno = EPERM; return (-1); } } } else if (execmode == directex) { cmdlen = copy_quote_and_fix_slashes(prog, cmdstr); cmdend = cmdstr + cmdlen; } if (execmode == none) { /* error: prog not found even after trying PATHEXT extensions */ errno = ENOENT; return (-1); } concat_args_and_quote(args, &cmdstr, &cmdlen, &cmdend, &cmdsize); if (*cmdstr == ' ') { /* if we left a ' ' for the quote and there is no quote */ cmdstr++; cmdlen--; } *cmdend = 0; init_startupinfo(&si); dwCreationflags = GetPriorityClass(GetCurrentProcess()); priority = GetThreadPriority(GetCurrentThread());#if defined(W32DEBUG) /* DebugView output is very difficult to read with overlong lines */ if (cmdlen < 128) dbgprintf(PR_EXEC, "%s(): CreateProcess(%s, ..) cmdstr=[%s]/n", __FUNCTION__, argv0, cmdstr); else { char shortbuf[128+4]; memcpy(shortbuf, cmdstr, 128); memcpy(shortbuf + 128, "...", 4); dbgprintf(PR_EXEC, "nt_execve(): CreateProcess(%s, ..) cmdstr=[%s]/n", argv0, shortbuf); }#endif if (!CreateProcess(argv0, cmdstr, NULL, NULL, TRUE, // need this for redirecting std handles dwCreationflags | CREATE_SUSPENDED, NULL, NULL, &si, &pi)) { exitcode = GetLastError(); if (exitcode == ERROR_BAD_EXE_FORMAT) { dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error BAD_EXE_FORMAT in %s/n", argv0, __FUNCTION__); errno = ENOEXEC; } else if (exitcode == ERROR_INVALID_PARAMETER) { dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error INVALID_PARAMETER in %s, cmdstr len=%u/n", argv0, __FUNCTION__, strlen(cmdstr)); /* exceeded command line */ /* return NOT found, ENAMETOOLONG is correct but not understood by the shell that will retry with another path ... */ errno = ENOENT; } else { dbgprintf(PR_ERROR, "!!! CreateProcess(%s, ..) error %ld in %s/n", argv0, exitcode, __FUNCTION__); errno = ENOENT; } goto fail_return; } else { exitcode = 0; if (!SetThreadPriority(pi.hThread, priority)) dbgprintf(PR_ERROR, "!!! SetThreadPriority(0x%p) failed, error %ld/n", pi.hThread, GetLastError()); ResumeThread(pi.hThread); if (!is_gui(argv0)) { if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0) dbgprintf(PR_ERROR, "!!! error %ld waiting for process %ld/n", GetLastError(), pi.dwProcessId); if (!GetExitCodeProcess(pi.hProcess, &exitcode)) dbgprintf(PR_ERROR, "!!! GetExitCodeProcess(0x%p, ..) error %ld in %s/n", pi.hProcess, GetLastError(), __FUNCTION__); } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); close_si_handles(); /* @@@@ should wait for the clipboard ? if (is_dev_clipboard_active) { CloseHandle((HANDLE)_get_osfhandle(0)); CloseHandle((HANDLE)_get_osfhandle(1)); CloseHandle((HANDLE)_get_osfhandle(2)); ... WaitForSingleObject(ghdevclipthread,60*1000); } */ dbgprintf(PR_ALL, "--- %s(): Exec'd process %ld terminated with exitcode %ld/n", __FUNCTION__, pi.dwProcessId, exitcode); exec_exit((int)exitcode); }fail_return: heap_free(cmdstr); close_si_handles(); exec_exit(-1); return (-1);}
开发者ID:oldfaber,项目名称:wzsh,代码行数:101,
示例28: AddToEFSFileBOOL WINAPI AddToEFSFile( IN EFSHANDLEFORWRITE hEFSFile, IN LPCSTR lpszFileName, IN DWORD dwComponentID, IN DWORD dwFileID, IN DWORD dwData, IN DWORD dwFlags){ assert(hEFSFile); assert(lpszFileName); // Check for unsupported flags. Right now all flags are unsupported. if (dwFlags) return FALSE; // Extract the EFS archive structure EFSFILEHANDLEFORWRITE *pEFSFile = (EFSFILEHANDLEFORWRITE *)hEFSFile; assert(pEFSFile->hFile != INVALID_HANDLE_VALUE); assert(pEFSFile->pDirectory); // If we've exceeded the number of entries in the directory table, we need to allocate a bigger one if (pEFSFile->nNumDirectoryEntries >= pEFSFile->nMaxDirectoryEntries) { DWORD nNumDirEntriesToAlloc = pEFSFile->nMaxDirectoryEntries * 2, nNumBytesToAlloc = nNumDirEntriesToAlloc * sizeof(EFSDIRECTORYENTRY); EFSDIRECTORYENTRY *pNewDirectory = (EFSDIRECTORYENTRY *)malloc(nNumBytesToAlloc); if (!pNewDirectory) return FALSE; // Copy the entrees over DWORD nNumBytesToCopy = pEFSFile->nMaxDirectoryEntries * sizeof(EFSDIRECTORYENTRY); memcpy(pNewDirectory, pEFSFile->pDirectory, nNumBytesToCopy); ZeroMemory((LPBYTE)pNewDirectory + nNumBytesToCopy, nNumBytesToAlloc - nNumBytesToCopy); // Replace the old directory entirely free(pEFSFile->pDirectory); pEFSFile->pDirectory = pNewDirectory; pEFSFile->nMaxDirectoryEntries = nNumDirEntriesToAlloc; } // Open the file to add to the EFS archive HANDLE hFile = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) return FALSE; // Add the file using AddUncompressedToEFSFile BOOL bRetVal = FALSE; // AddUncompressedToEFSFile may trash the directory even if the addition fails, so we need to make sure we always write it again (mark the archive as modified) pEFSFile->bModified = TRUE; EFSDIRECTORYENTRY *pDirEntry = &pEFSFile->pDirectory[pEFSFile->nNumDirectoryEntries]; if (AddUncompressedToEFSFile(pEFSFile, hFile, pDirEntry)) { // Success. Fill in the file data not filled in by AddUncompressedToEFSFile. pDirEntry->dwComponentID = dwComponentID; pDirEntry->dwFileID = dwFileID; pDirEntry->dwData = dwData; pDirEntry->dwFlags = 0; // Update the archive state pEFSFile->dwInsertPoint += pDirEntry->dwSize; pEFSFile->nNumDirectoryEntries++; bRetVal = TRUE; } CloseHandle(hFile); return bRetVal;}
开发者ID:crabminister,项目名称:Coffee,代码行数:74,
注:本文中的CloseHandle函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 C++ CloseLogFile函数代码示例 C++ CloseFile函数代码示例 |