/*---------------------------------------------------------------------- | NPT_Win32Mutex::NPT_Win32Mutex +---------------------------------------------------------------------*/ NPT_Win32Mutex::NPT_Win32Mutex() { m_Handle = CreateMutex(NULL, FALSE, NULL); }
#include "CornerTurnConst.h" #include "OrderHistoryData.h" #include "OpenOrderData.h" #include "PositionUpdate.h" #include "AccountData.h" #include "PurchaseData.h" #include "PurchaseManager.h" #include "SymbolData.h" #include "SymbolDataList.h" #include "PositionMonitorManager.h" #include "TimeZone.h" PositionManager * PositionManager::instance_ = 0; HANDLE mutex_ = CreateMutex (NULL, // no security attributes FALSE, // initially not owned "MutexToProtectCriticalSection"); // name of mutex PositionManager * PositionManager::instance() { if(0 == instance_) { instance_ = new PositionManager(); } return instance_; } PositionManager::PositionManager() { }
/* * init_resolve_thread() starts a new thread that performs the actual * resolve. This function returns before the resolve is done. * * Returns FALSE in case of failure, otherwise TRUE. */ static bool init_resolve_thread (struct connectdata *conn, const char *hostname, int port, const struct addrinfo *hints) { struct thread_data *td = calloc(sizeof(*td), 1); HANDLE thread_and_event[2] = {0}; if (!td) { SET_ERRNO(ENOMEM); return FALSE; } Curl_safefree(conn->async.hostname); conn->async.hostname = strdup(hostname); if (!conn->async.hostname) { free(td); SET_ERRNO(ENOMEM); return FALSE; } conn->async.port = port; conn->async.done = FALSE; conn->async.status = 0; conn->async.dns = NULL; conn->async.os_specific = (void*) td; td->dummy_sock = CURL_SOCKET_BAD; /* Create the mutex used to inform the resolver thread that we're * still waiting, and take initial ownership. */ td->mutex_waiting = CreateMutex(NULL, TRUE, NULL); if (td->mutex_waiting == NULL) { Curl_destroy_thread_data(&conn->async); SET_ERRNO(EAGAIN); return FALSE; } /* Create the event that the thread uses to inform us that it's * done resolving. Do not signal it. */ td->event_resolved = CreateEvent(NULL, TRUE, FALSE, NULL); if (td->event_resolved == NULL) { Curl_destroy_thread_data(&conn->async); SET_ERRNO(EAGAIN); return FALSE; } /* Create the mutex used to serialize access to event_terminated * between us and resolver thread. */ td->mutex_terminate = CreateMutex(NULL, FALSE, NULL); if (td->mutex_terminate == NULL) { Curl_destroy_thread_data(&conn->async); SET_ERRNO(EAGAIN); return FALSE; } /* Create the event used to signal thread that it should terminate. */ td->event_terminate = CreateEvent(NULL, TRUE, FALSE, NULL); if (td->event_terminate == NULL) { Curl_destroy_thread_data(&conn->async); SET_ERRNO(EAGAIN); return FALSE; } /* Create the event used by thread to inform it has initialized its own data. */ td->event_thread_started = CreateEvent(NULL, TRUE, FALSE, NULL); if (td->event_thread_started == NULL) { Curl_destroy_thread_data(&conn->async); SET_ERRNO(EAGAIN); return FALSE; } #ifdef _WIN32_WCE td->thread_hnd = (HANDLE) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) THREAD_FUNC, conn, 0, &td->thread_id); #else td->thread_hnd = (HANDLE) _beginthreadex(NULL, 0, THREAD_FUNC, conn, 0, &td->thread_id); #endif #ifdef CURLRES_IPV6 DEBUGASSERT(hints); td->hints = *hints; #else (void) hints; #endif if (!td->thread_hnd) { #ifndef _WIN32_WCE SET_ERRNO(errno); #endif Curl_destroy_thread_data(&conn->async); return FALSE; } /* Waiting until the thread will initialize its data or it will exit due errors. */ thread_and_event[0] = td->thread_hnd; thread_and_event[1] = td->event_thread_started; if (WaitForMultipleObjects(sizeof(thread_and_event) / sizeof(thread_and_event[0]), (const HANDLE*)thread_and_event, FALSE, INFINITE) == WAIT_FAILED) { /* The resolver thread has been created, * most probably it works now - ignoring this "minor" error */ } /* This socket is only to keep Curl_resolv_fdset() and select() happy; * should never become signalled for read/write since it's unbound but * Windows needs atleast 1 socket in select(). */ td->dummy_sock = socket(AF_INET, SOCK_DGRAM, 0); return TRUE; }
//Main program int main() { int i,n=0,j=0; float diff; FMOD_SYSTEM *fmod = 0; FMOD_RESULT result; //establish COM communication if(serial_start(TEXT("COM7")) != 0) { printf("Error while establishing COM connection!\n"); system("PAUSE"); exit(1); } Sleep(1000);//sleep so that uC can clear LEDs' status //FMOD result = FMOD_System_Create(&fmod); if(result != FMOD_OK) { printf("FMOD Error"); exit(1); } //Mutex stopAppMutex = CreateMutex(NULL,NULL,NULL); _stopApp = FALSE; spectrumMutex = CreateMutex(NULL,NULL,NULL); for(i = 0;i<8;i++) { analyzedSpectrum[i] = 0; } //FMOD listening thread _beginthread(getSpectrum, 0, fmod); //Network thread //_beginthread(notifyLightshow, 0, NULL); //control LEDs n=0; while(1) { //clear for(i = 0;i<25;i++){ buf[0+i*3]=0x00; buf[1+i*3]=0x00; buf[2+i*3]=0x00; } WaitForSingleObject(spectrumMutex, INFINITE); for( i =0;i<5;i++) { diff = abs((analyzedSpectrum[i]/10-previousAnalyzedSpectrum[i]/10)*10); switch(i) { case 0: barsToLEDMapping(0,diff); break; case 1: barsToLEDMapping(1,diff); break; case 2: barsToLEDMapping(2,diff); break; case 3: barsToLEDMapping(3,diff); break; case 4: barsToLEDMapping(4,diff); break; } previousAnalyzedSpectrum[i]=analyzedSpectrum[i]; } ReleaseMutex(spectrumMutex); serial_write(buf, 3*25); } //cleanup CloseHandle(comPort); system("PAUSE"); return 0; }
void __cdecl InitGui(void *param) { HWND hparentwnd; HANDLE hinst; WNDCLASSEX wndclass; char szFile[80]; hinst = GetModuleHandle(NULL); GetModuleFileName (hinst, szFile, sizeof(szFile)); #ifdef DEBUG printf ("hinst = %x\n", hinst); printf ("File = %s\n", szFile); #endif /* Fill in window class structure with parameters that describe the main window. */ /* CS_OWNDC : un DC pour chaque fenêtre de la classe */ wndclass.cbSize = sizeof(wndclass); wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndclass.lpfnWndProc = (WNDPROC)WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hinst; wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION); wndclass.hIconSm = LoadIcon (NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = GetStockObject(WHITE_BRUSH); wndclass.lpszClassName = szFile; wndclass.lpszMenuName = NULL; if (!RegisterClassEx(&wndclass)) Win32Error("Register class"); hparentwnd = GetFocus(); my_window = CreateWindow(szFile, szTitle, WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, /* screenwidth, screendepth, */ hparentwnd, NULL, hinst, NULL); if (!my_window) { Win32Error("Create window"); } #ifdef DEBUG fprintf(stderr, "my_window = %x\n", my_window); #endif #ifdef LOOPMSG /* Acknowledge for UpdateWindow() (WM_PAINT message generated) */ hMutex = CreateMutex(NULL, FALSE, "DrawingMutex"); my_dc = GetDC(my_window); /* Device context for drawing and the associated bitmap. */ drawing_dc = CreateCompatibleDC(my_dc); hbm = CreateCompatibleBitmap(my_dc, screenwidth, screendepth); SelectObject(drawing_dc, hbm); /* Blank the bitmap */ SelectObject(drawing_dc, GetStockObject(WHITE_BRUSH)); PatBlt(drawing_dc, 0, 0, screenwidth, screendepth, PATCOPY); hAccelTable = LoadAccelerators (hinst, szTitle); ShowWindow(my_window, SW_SHOWNORMAL); UpdateWindow(my_window); /* Running the message loop */ while (GetMessage(&msg, my_window, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } #else drawing_dc = my_dc = GetDC(my_window); #endif }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR cmd, int nCmdShow) { utox_mutex_handle = CreateMutex(NULL, 0, UTOX_TITLE); if (!utox_mutex_handle) { return 0; } if (GetLastError() == ERROR_ALREADY_EXISTS) { HWND window = FindWindow(UTOX_TITLE, NULL); /* uTox is running. */ if (window) { SetForegroundWindow(window); } return 0; } MY_CMD_ARGS = cmd; MY_HINSTANCE = hInstance; TOX_UPDATER_PATH_LEN = GetModuleFileName(NULL, TOX_UPDATER_PATH, MAX_PATH); TOX_UPDATER_PATH[TOX_UPDATER_PATH_LEN] = 0; { char path[MAX_PATH], *s; memcpy(path, TOX_UPDATER_PATH, TOX_UPDATER_PATH_LEN + 1); s = path + TOX_UPDATER_PATH_LEN; while(*s != '\\') { s--; } *s = 0; SetCurrentDirectory(path); } LPWSTR *arglist; int argc, i; init_tox_version_name(); /* Convert PSTR command line args from windows to argc */ arglist = CommandLineToArgvW(GetCommandLineW(), &argc); if( NULL != arglist ){ for (i = 0; i < argc; i++) { if(wcscmp(arglist[i], L"--uninstall") == 0) { if (is_tox_installed) { uninstall_tox(); return 0; } } } } LOG_FILE = fopen("tox_log.txt", "w"); /* initialize winsock */ WSADATA wsaData; if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { LOG_TO_FILE("WSAStartup failed\n"); return 1; } if (IsWindowsVistaOrGreater()) { /* check if we are on a 64-bit system */ _Bool iswow64 = 0; _Bool (WINAPI *fnIsWow64Process)(HANDLE, _Bool*) = (void*)GetProcAddress(GetModuleHandleA("kernel32"),"IsWow64Process"); if(fnIsWow64Process) { fnIsWow64Process(GetCurrentProcess(), &iswow64); } if(iswow64) { /* replace the arch in the GET_NAME/TOX_VERSION_NAME strings (todo: not use constants for offsets) */ GET_NAME[3] = '6'; GET_NAME[4] = '4'; TOX_VERSION_NAME[0] = '6'; TOX_VERSION_NAME[1] = '4'; LOG_TO_FILE("detected 64bit system\n"); } else { GET_NAME[3] = '3'; GET_NAME[4] = '2'; TOX_VERSION_NAME[0] = '3'; TOX_VERSION_NAME[1] = '2'; LOG_TO_FILE("detected 32bit system\n"); } } else { GET_NAME[3] = 'x'; GET_NAME[4] = 'p'; TOX_VERSION_NAME[0] = 'x'; TOX_VERSION_NAME[1] = 'p'; LOG_TO_FILE("detected XP system\n"); } /* init common controls */ INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = ICC_PROGRESS_CLASS; InitCommonControlsEx(&InitCtrlEx); main_window = CreateDialog(MY_HINSTANCE, MAKEINTRESOURCE(IDD_MAIN_DIALOG), NULL, MainDialogProc); if (!main_window) { LOG_TO_FILE("error creating main window %lu\n", GetLastError()); exit(0); } progressbar = GetDlgItem(main_window, ID_PROGRESSBAR); set_download_progress(0); status_label = GetDlgItem(main_window, IDC_STATUS_LABEL); if (!is_tox_installed) { // show installer controls HWND desktop_shortcut_checkbox = GetDlgItem(main_window, ID_DESKTOP_SHORTCUT_CHECKBOX); Button_SetCheck(desktop_shortcut_checkbox, 1); ShowWindow(desktop_shortcut_checkbox, SW_SHOW); HWND startmenu_shortcut_checkbox = GetDlgItem(main_window, ID_STARTMENU_SHORTCUT_CHECKBOX); Button_SetCheck(startmenu_shortcut_checkbox, 1); ShowWindow(startmenu_shortcut_checkbox, SW_SHOW); HWND start_on_boot_checkbox = GetDlgItem(main_window, ID_START_ON_BOOT_CHECKBOX); Button_SetCheck(start_on_boot_checkbox, 1); ShowWindow(start_on_boot_checkbox, SW_SHOW); ShowWindow(GetDlgItem(main_window, ID_TOX_URL_CHECKBOX), SW_SHOW); wchar_t appdatalocal_path[MAX_PATH] = {0}; if (SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, appdatalocal_path) == S_OK) { set_utox_path(appdatalocal_path); } Button_Enable(GetDlgItem(main_window, ID_INSTALL_BUTTON), 0); ShowWindow(GetDlgItem(main_window, ID_INSTALL_BUTTON), SW_SHOW); Edit_SetReadOnly(GetDlgItem(main_window, ID_BROWSE_TEXTBOX), 1); ShowWindow(GetDlgItem(main_window, ID_BROWSE_TEXTBOX), SW_SHOW); ShowWindow(GetDlgItem(main_window, ID_BROWSE_BUTTON), SW_SHOW); ShowWindow(GetDlgItem(main_window, IDC_INSTALL_FOLDER_LABEL), SW_SHOW); ShowWindow(main_window, SW_SHOW); } _beginthread(check_updates, 0, NULL); MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { DispatchMessage(&msg); } open_utox_and_exit(); return 0; }
//----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR commandLine, INT ) { // set up some xbmc specific relationships XBMC::Context context; //this can't be set from CAdvancedSettings::Initialize() because it will overwrite //the loglevel set with the --debug flag #ifdef _DEBUG g_advancedSettings.m_logLevel = LOG_LEVEL_DEBUG; g_advancedSettings.m_logLevelHint = LOG_LEVEL_DEBUG; #else g_advancedSettings.m_logLevel = LOG_LEVEL_NORMAL; g_advancedSettings.m_logLevelHint = LOG_LEVEL_NORMAL; #endif CLog::SetLogLevel(g_advancedSettings.m_logLevel); // Initializes CreateMiniDump to handle exceptions. win32_exception::set_version(g_infoManager.GetVersion()); SetUnhandledExceptionFilter( CreateMiniDump ); // check if XBMC is already running CreateMutex(NULL, FALSE, "XBMC Media Center"); if(GetLastError() == ERROR_ALREADY_EXISTS) { HWND m_hwnd = FindWindow("XBMC","XBMC"); if(m_hwnd != NULL) { // switch to the running instance ShowWindow(m_hwnd,SW_RESTORE); SetForegroundWindow(m_hwnd); } return 0; } #ifndef HAS_DX if(CWIN32Util::GetDesktopColorDepth() < 32) { //FIXME: replace it by a SDL window for all ports MessageBox(NULL, "Desktop Color Depth isn't 32Bit", "XBMC: Fatal Error", MB_OK|MB_ICONERROR); return 0; } #endif if((g_cpuInfo.GetCPUFeatures() & CPU_FEATURE_SSE2) == 0) { MessageBox(NULL, "No SSE2 support detected", "XBMC: Fatal Error", MB_OK|MB_ICONERROR); return 0; } //Initialize COM CoInitializeEx(NULL, COINIT_MULTITHREADED); // Handle numeric values using the default/POSIX standard setlocale(LC_NUMERIC, "C"); // If the command line passed to WinMain, commandLine, is not "" we need // to process the command line arguments. // Note that commandLine does not include the program name and can be // equal to "" if no arguments were supplied. By contrast GetCommandLineW() // does include the program name and is never equal to "". g_advancedSettings.Initialize(); if (strlen(commandLine) != 0) { int argc; LPWSTR* argvW = CommandLineToArgvW(GetCommandLineW(), &argc); std::vector<std::string> strargvA; strargvA.resize(argc); const char** argv = (const char**) LocalAlloc(LMEM_FIXED, argc*sizeof(char*)); for (int i = 0; i < argc; i++) { g_charsetConverter.wToUTF8(argvW[i], strargvA[i]); argv[i] = strargvA[i].c_str(); } // Parse the arguments CAppParamParser appParamParser; appParamParser.Parse(argv, argc); // Clean up the storage we've used LocalFree(argvW); LocalFree(argv); } // Initialise Winsock WSADATA wd; WSAStartup(MAKEWORD(2,2), &wd); // use 1 ms timer precision - like SDL initialization used to do timeBeginPeriod(1); #ifdef XBMC_TRACK_EXCEPTIONS try { #endif // Create and run the app if(!g_application.Create()) { MessageBox(NULL, "ERROR: Unable to create application. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #ifdef XBMC_TRACK_EXCEPTIONS } catch (const XbmcCommons::UncheckedException &e) { e.LogThrowMessage("CApplication::Create()"); MessageBox(NULL, "ERROR: Unable to create application. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } catch (...) { CLog::Log(LOGERROR, "exception in CApplication::Create()"); MessageBox(NULL, "ERROR: Unable to create application. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #endif #ifndef _DEBUG // we don't want to see the "no disc in drive" windows message box SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX); #endif #ifdef XBMC_TRACK_EXCEPTIONS try { #endif if (!g_application.CreateGUI()) { MessageBox(NULL, "ERROR: Unable to create GUI. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #ifdef XBMC_TRACK_EXCEPTIONS } catch (const XbmcCommons::UncheckedException &e) { e.LogThrowMessage("CApplication::CreateGUI()"); MessageBox(NULL, "ERROR: Unable to create GUI. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } catch (...) { CLog::Log(LOGERROR, "exception in CApplication::CreateGUI()"); MessageBox(NULL, "ERROR: Unable to create GUI. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #endif #ifdef XBMC_TRACK_EXCEPTIONS try { #endif if (!g_application.Initialize()) { MessageBox(NULL, "ERROR: Unable to Initialize. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #ifdef XBMC_TRACK_EXCEPTIONS } catch (const XbmcCommons::UncheckedException &e) { e.LogThrowMessage("CApplication::Initialize()"); MessageBox(NULL, "ERROR: Unable to Initialize. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } catch (...) { CLog::Log(LOGERROR, "exception in CApplication::Initialize()"); MessageBox(NULL, "ERROR: Unable to Initialize. Exiting.", "XBMC: Error", MB_OK|MB_ICONERROR); return 1; } #endif g_application.Run(); // clear previously set timer resolution timeEndPeriod(1); // the end WSACleanup(); CoUninitialize(); return 0; }
int WINAPI wWinMain(_In_ HINSTANCE Program, _In_opt_ HINSTANCE PreviousProgram, _In_ LPWSTR CommandLine, _In_ int ShowCommand) { UNREFERENCED_PARAMETER(PreviousProgram); UNREFERENCED_PARAMETER(CommandLine); UNREFERENCED_PARAMETER(ShowCommand); #ifndef _XBOX HRESULT hr = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED); if (FAILED(hr)) return 1; #endif // make sure this is the only instance of this game running on the computer if not then close application const char szUniqueNamedMutex[] = "punchdrunksquirrelgames_bloodnoir"; HANDLE hHandle = CreateMutex(NULL, TRUE, szUniqueNamedMutex); if (ERROR_ALREADY_EXISTS == GetLastError()) { // Program already running somewhere return(1); // Exit program } // create the game object m_game = make_unique<Game>(); // initialize the window class if (!InitWindowClass(Program)) return 1; // display the window on the screen ShowWindow(m_window, SW_MAXIMIZE); SetWindowLongPtr(m_window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(m_game.get())); GetClientRect(m_window, &rc); // initialize the game if (!m_game->GameInitialize(m_window, rc.right - rc.left, rc.bottom - rc.top)) return 0; // enter the message loop only leaving it when the Quit message is received MSG msg = { 0 }; while (msg.message != WM_QUIT) { if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { m_game->GameRun(); } } // if loop exists then reset game object m_game.reset(); // release things that need to be released and return control to windows CoUninitialize(); ReleaseMutex(hHandle); // Explicitly release mutex CloseHandle(hHandle); // close handle before terminating return (int)msg.wParam; }
int __declspec(dllexport) DLL_Init() { if (!hMutex) hMutex = CreateMutex(NULL,false,NULL); return 0; }
void system_Configure( libvlc_int_t *p_this, int *pi_argc, const char *ppsz_argv[] ) { #if !defined( UNDER_CE ) /* Raise default priority of the current process */ #ifndef ABOVE_NORMAL_PRIORITY_CLASS # define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000 #endif if( config_GetInt( p_this, "high-priority" ) ) { if( SetPriorityClass( GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS ) || SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) ) { msg_Dbg( p_this, "raised process priority" ); } else { msg_Dbg( p_this, "could not raise process priority" ); } } if( config_GetInt( p_this, "one-instance" ) || ( config_GetInt( p_this, "one-instance-when-started-from-file" ) && config_GetInt( p_this, "started-from-file" ) ) ) { HANDLE hmutex; msg_Info( p_this, "one instance mode ENABLED"); /* Use a named mutex to check if another instance is already running */ if( !( hmutex = CreateMutex( 0, TRUE, L"VLC ipc "VERSION ) ) ) { /* Failed for some reason. Just ignore the option and go on as * normal. */ msg_Err( p_this, "one instance mode DISABLED " "(mutex couldn't be created)" ); return; } if( GetLastError() != ERROR_ALREADY_EXISTS ) { /* We are the 1st instance. */ static const char typename[] = "ipc helper"; p_helper = vlc_custom_create( p_this, sizeof(vlc_object_t), VLC_OBJECT_GENERIC, typename ); /* Run the helper thread */ hIPCHelperReady = CreateEvent( NULL, FALSE, FALSE, NULL ); hIPCHelper = _beginthreadex( NULL, 0, IPCHelperThread, p_helper, 0, NULL ); if( hIPCHelper ) WaitForSingleObject( hIPCHelperReady, INFINITE ); else { msg_Err( p_this, "one instance mode DISABLED " "(IPC helper thread couldn't be created)" ); vlc_object_release (p_helper); p_helper = NULL; } vlc_object_attach (p_helper, p_this); CloseHandle( hIPCHelperReady ); /* Initialization done. * Release the mutex to unblock other instances */ ReleaseMutex( hmutex ); } else {
FacebookProto::FacebookProto(const char* proto_name,const TCHAR* username) : PROTO<FacebookProto>(proto_name, username) { facy.parent = this; signon_lock_ = CreateMutex(NULL, FALSE, NULL); avatar_lock_ = CreateMutex(NULL, FALSE, NULL); log_lock_ = CreateMutex(NULL, FALSE, NULL); update_loop_lock_ = CreateEvent(NULL, FALSE, FALSE, NULL); facy.buddies_lock_ = CreateMutex(NULL, FALSE, NULL); facy.send_message_lock_ = CreateMutex(NULL, FALSE, NULL); facy.fcb_conn_lock_ = CreateMutex(NULL, FALSE, NULL); m_invisible = false; CreateProtoService(PS_CREATEACCMGRUI, &FacebookProto::SvcCreateAccMgrUI); CreateProtoService(PS_GETMYAWAYMSG, &FacebookProto::GetMyAwayMsg); CreateProtoService(PS_GETMYAVATART, &FacebookProto::GetMyAvatar); CreateProtoService(PS_GETAVATARINFOT, &FacebookProto::GetAvatarInfo); CreateProtoService(PS_GETAVATARCAPS, &FacebookProto::GetAvatarCaps); CreateProtoService(PS_GETUNREADEMAILCOUNT, &FacebookProto::GetNotificationsCount); CreateProtoService(PS_JOINCHAT, &FacebookProto::OnJoinChat); CreateProtoService(PS_LEAVECHAT, &FacebookProto::OnLeaveChat); CreateProtoService("/Mind", &FacebookProto::OnMind); CreateProtoService("/VisitProfile", &FacebookProto::VisitProfile); CreateProtoService("/VisitNotifications", &FacebookProto::VisitNotifications); HookProtoEvent(ME_CLIST_PREBUILDSTATUSMENU, &FacebookProto::OnBuildStatusMenu); HookProtoEvent(ME_OPT_INITIALISE, &FacebookProto::OnOptionsInit); HookProtoEvent(ME_IDLE_CHANGED, &FacebookProto::OnIdleChanged); HookProtoEvent(ME_TTB_MODULELOADED, &FacebookProto::OnToolbarInit); HookProtoEvent(ME_GC_EVENT, &FacebookProto::OnGCEvent); HookProtoEvent(ME_GC_BUILDMENU, &FacebookProto::OnGCMenuHook); HookProtoEvent(ME_DB_EVENT_MARKED_READ, &FacebookProto::OnDbEventRead); HookProtoEvent(ME_MSG_WINDOWEVENT, &FacebookProto::OnProcessSrmmEvent); db_set_resident(m_szModuleName, "Status"); db_set_resident(m_szModuleName, "IdleTS"); InitHotkeys(); InitPopups(); InitSounds(); // Create standard network connection TCHAR descr[512]; NETLIBUSER nlu = {sizeof(nlu)}; nlu.flags = NUF_INCOMING | NUF_OUTGOING | NUF_HTTPCONNS | NUF_TCHAR; nlu.szSettingsModule = m_szModuleName; mir_sntprintf(descr, SIZEOF(descr), TranslateT("%s server connection"), m_tszUserName); nlu.ptszDescriptiveName = descr; m_hNetlibUser = (HANDLE)CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM)&nlu); if (m_hNetlibUser == NULL) MessageBox(NULL, TranslateT("Unable to get Netlib connection for Facebook"), m_tszUserName, MB_OK); facy.set_handle(m_hNetlibUser); // Set all contacts offline -- in case we crashed SetAllContactStatuses(ID_STATUS_OFFLINE); }
VOS_S32 __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdLine, VOS_S32 show) { DCSP_USAGE_OPTIONS *options; VOS_U16 ai_name_msg[] = {0, 34, DCSP_HST_NME, DCSP_HST_BRACKET_OPEN, DCSP_HST_CHAR('h'), DCSP_HST_CHAR('o'), DCSP_HST_CHAR('l'), DCSP_HST_CHAR('d'), DCSP_HST_CHAR('b'), DCSP_HST_CHAR('o'), DCSP_HST_CHAR('t'), DCSP_HST_BRACKET_CLOSE, DCSP_HST_BRACKET_OPEN, DCSP_HST_CHAR('0'), DCSP_HST_CHAR('0'), DCSP_HST_CHAR('.'), DCSP_HST_CHAR('0'), DCSP_HST_CHAR('1'), DCSP_HST_BRACKET_CLOSE}; VOS_BOOL keep_going = TRUE; HLDB_THREAD_DATA *thread_data = NULL; HLDB_MSG *hldb_msg; VOS_S32 wait_rc; HLDB_LOCAL_DATA local; VOS_CHAR *host = "localhost"; VOS_U8 host_type = DCSP_ADDR_FORMAT_HOST_NAME; VOS_U16 port = 16713; VOS_UNREFERENCED_PARAMETER(hInst); VOS_UNREFERENCED_PARAMETER(hPrevInst); VOS_UNREFERENCED_PARAMETER(show); /***************************************************************************/ /* Set-up the message type for the NME message. */ /***************************************************************************/ *((VOS_U8 *)ai_name_msg) = DCSP_MSG_TYPE_DM; /***************************************************************************/ /* Check and set the options from the command line. */ /***************************************************************************/ if (!hldb_set_parameters(cmdLine, &host, &host_type, &port)) { MessageBox( NULL, "Syntax: holdbot [-nhost_name|-iip_address] [-pport]", "Hold-bot", 0); goto EXIT_LABEL; } /***************************************************************************/ /* Allocate thread-control objects. */ /***************************************************************************/ thread_data = malloc(sizeof(HLDB_THREAD_DATA)); if (thread_data == NULL) { MessageBox(NULL, "Out of memory", "Hold-bot", 0); goto EXIT_LABEL; } thread_data->semaphore = CreateSemaphore(NULL, 0, VOS_MAX_PSINT, NULL); thread_data->mutex = CreateMutex(NULL, FALSE, NULL); if ((thread_data->semaphore == NULL) || (thread_data->mutex == NULL)) { MessageBox(NULL, "Failed to allocate thread controls", "Hold-bot", 0); goto EXIT_LABEL; } VOS_Q_INIT_ROOT(thread_data->msg_q); /***************************************************************************/ /* Initialise the local data. */ /***************************************************************************/ local.power = 0; local.num_scs = 0; /***************************************************************************/ /* Set up the client options. For ease of use, the holdbot uses */ /* Host-Order messages. (Real AIs will probably wish to use network order */ /* to improve performance.) */ /***************************************************************************/ options = dcsp_configure("holdbot.cfg"); options->client = TRUE; options->scheduling = DCSP_SCHEDULE_THREAD; options->notification = DCSP_NOTIFICATION_CALLBACK; options->representation = DCSP_REPRESENTATION_HOST_ORDER; options->message_callback = hldb_receive_message; options->message_callback_data = (VOS_VOID *)thread_data; /***************************************************************************/ /* Initialise the DLL. */ /***************************************************************************/ if (!dcsp_start(options)) { MessageBox(NULL, "Failed to initialise the DLL", "Hold-bot", 0); goto EXIT_LABEL; } /***************************************************************************/ /* Display an error message and exit if the server details aren't valid. */ /***************************************************************************/ if (!dcsp_convert_address(host, host_type, port)) { MessageBox(NULL, "Invalid server address (check -n/-i parameter).", "Hold-bot", 0); goto EXIT_LABEL; } /***************************************************************************/ /* Open a connection to the specified server. Default is localhost:16713. */ /***************************************************************************/ dcsp_client_connect(); /***************************************************************************/ /* Send the NME message. */ /***************************************************************************/ dcsp_client_send_message((VOS_CHAR *)ai_name_msg, sizeof(ai_name_msg)); do { /*************************************************************************/ /* Wait for a message. */ /*************************************************************************/ wait_rc = WaitForSingleObject(thread_data->semaphore, INFINITE); VOS_ASSERT((wait_rc == WAIT_ABANDONED) || (wait_rc == WAIT_OBJECT_0)); /*************************************************************************/ /* If a message is waiting, process it. */ /*************************************************************************/ wait_rc = WaitForSingleObject(thread_data->mutex, INFINITE); hldb_msg = (HLDB_MSG *)VOS_Q_FIRST(thread_data->msg_q); VOS_ASSERT(hldb_msg != NULL); VOS_Q_DEQUEUE(hldb_msg->q_hdr, thread_data->msg_q); ReleaseMutex(thread_data->mutex); /*************************************************************************/ /* Process and free the message. */ /*************************************************************************/ keep_going = hldb_process_msg(&local, ((VOS_CHAR *)(hldb_msg)) + sizeof(HLDB_MSG)); free(hldb_msg); } while (keep_going); /***************************************************************************/ /* Stop the protocol DLL. */ /***************************************************************************/ dcsp_stop(); EXIT_LABEL: /***************************************************************************/ /* Tidy up the thread data. */ /***************************************************************************/ if (thread_data != NULL) { /*************************************************************************/ /* Free the semaphore if it exists. */ /*************************************************************************/ if (thread_data->semaphore != NULL) { CloseHandle(thread_data->semaphore); } /*************************************************************************/ /* Free the mutex if it exists. */ /*************************************************************************/ if (thread_data->mutex != NULL) { CloseHandle(thread_data->mutex); } /*************************************************************************/ /* Free the memory. */ /*************************************************************************/ free(thread_data); } return(0); }
static BOOL _winpr_openssl_initialize_locking(void) { int i, count; /* OpenSSL static locking */ if (CRYPTO_get_locking_callback()) { WLog_WARN(TAG, "OpenSSL static locking callback is already set"); } else { if ((count = CRYPTO_num_locks()) > 0) { HANDLE* locks; if (!(locks = calloc(count, sizeof(HANDLE)))) { WLog_ERR(TAG, "error allocating lock table"); return FALSE; } for (i = 0; i < count; i++) { if (!(locks[i] = CreateMutex(NULL, FALSE, NULL))) { WLog_ERR(TAG, "error creating lock #%d", i); while (i--) { if (locks[i]) CloseHandle(locks[i]); } free(locks); return FALSE; } } g_winpr_openssl_locks = locks; g_winpr_openssl_num_locks = count; CRYPTO_set_locking_callback(_winpr_openssl_locking); } } /* OpenSSL dynamic locking */ if (CRYPTO_get_dynlock_create_callback() || CRYPTO_get_dynlock_lock_callback() || CRYPTO_get_dynlock_destroy_callback()) { WLog_WARN(TAG, "dynamic locking callbacks are already set"); } else { CRYPTO_set_dynlock_create_callback(_winpr_openssl_dynlock_create); CRYPTO_set_dynlock_lock_callback(_winpr_openssl_dynlock_lock); CRYPTO_set_dynlock_destroy_callback(_winpr_openssl_dynlock_destroy); } /* Use the deprecated CRYPTO_get_id_callback() if building against OpenSSL < 1.0.0 */ #if (OPENSSL_VERSION_NUMBER < 0x10000000L) if (CRYPTO_get_id_callback()) { WLog_WARN(TAG, "OpenSSL id_callback is already set"); } else { CRYPTO_set_id_callback(_winpr_openssl_id); } #endif return TRUE; }
void ngx_master_process_cycle(ngx_cycle_t *cycle) { u_long nev, ev, timeout; ngx_err_t err; ngx_int_t n; ngx_msec_t timer; ngx_uint_t live; HANDLE events[MAXIMUM_WAIT_OBJECTS]; ngx_sprintf((u_char *) ngx_master_process_event_name, "ngx_master_%s%Z", ngx_unique); if (ngx_process == NGX_PROCESS_WORKER) { ngx_worker_process_cycle(cycle, ngx_master_process_event_name); return; } ngx_log_debug0(NGX_LOG_DEBUG_CORE, cycle->log, 0, "master started"); ngx_console_init(cycle); SetEnvironmentVariable("ngx_unique", ngx_unique); ngx_master_process_event = CreateEvent(NULL, 1, 0, ngx_master_process_event_name); if (ngx_master_process_event == NULL) { ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, "CreateEvent(\"%s\") failed", ngx_master_process_event_name); exit(2); } if (ngx_create_signal_events(cycle) != NGX_OK) { exit(2); } ngx_sprintf((u_char *) ngx_cache_manager_mutex_name, "ngx_cache_manager_mutex_%s%Z", ngx_unique); ngx_cache_manager_mutex = CreateMutex(NULL, 0, ngx_cache_manager_mutex_name); if (ngx_cache_manager_mutex == NULL) { ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno, "CreateMutex(\"%s\") failed", ngx_cache_manager_mutex_name); exit(2); } events[0] = ngx_stop_event; events[1] = ngx_quit_event; events[2] = ngx_reopen_event; events[3] = ngx_reload_event; ngx_close_listening_sockets(cycle); if (ngx_start_worker_processes(cycle, NGX_PROCESS_RESPAWN) == 0) { exit(2); } timer = 0; timeout = INFINITE; for ( ;; ) { nev = 4; for (n = 0; n < ngx_last_process; n++) { if (ngx_processes[n].handle) { events[nev++] = ngx_processes[n].handle; } } if (timer) { timeout = timer > ngx_current_msec ? timer - ngx_current_msec : 0; } ev = WaitForMultipleObjects(nev, events, 0, timeout); err = ngx_errno; ngx_time_update(); ngx_log_debug1(NGX_LOG_DEBUG_CORE, cycle->log, 0, "master WaitForMultipleObjects: %ul", ev); if (ev == WAIT_OBJECT_0) { ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "exiting"); if (ResetEvent(ngx_stop_event) == 0) { ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, "ResetEvent(\"%s\") failed", ngx_stop_event_name); } if (timer == 0) { timer = ngx_current_msec + 5000; } ngx_terminate = 1; ngx_quit_worker_processes(cycle, 0); continue; } if (ev == WAIT_OBJECT_0 + 1) { ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "shutting down"); if (ResetEvent(ngx_quit_event) == 0) { ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, "ResetEvent(\"%s\") failed", ngx_quit_event_name); } ngx_quit = 1; ngx_quit_worker_processes(cycle, 0); continue; } if (ev == WAIT_OBJECT_0 + 2) { ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reopening logs"); if (ResetEvent(ngx_reopen_event) == 0) { ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, "ResetEvent(\"%s\") failed", ngx_reopen_event_name); } ngx_reopen_files(cycle, -1); ngx_reopen_worker_processes(cycle); continue; } if (ev == WAIT_OBJECT_0 + 3) { ngx_log_error(NGX_LOG_NOTICE, cycle->log, 0, "reconfiguring"); if (ResetEvent(ngx_reload_event) == 0) { ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, "ResetEvent(\"%s\") failed", ngx_reload_event_name); } cycle = ngx_init_cycle(cycle); if (cycle == NULL) { cycle = (ngx_cycle_t *) ngx_cycle; continue; } ngx_cycle = cycle; ngx_close_listening_sockets(cycle); if (ngx_start_worker_processes(cycle, NGX_PROCESS_JUST_RESPAWN)) { ngx_quit_worker_processes(cycle, 1); } continue; } if (ev > WAIT_OBJECT_0 + 3 && ev < WAIT_OBJECT_0 + nev) { ngx_log_debug0(NGX_LOG_DEBUG_CORE, cycle->log, 0, "reap worker"); live = ngx_reap_worker(cycle, events[ev]); if (!live && (ngx_terminate || ngx_quit)) { ngx_master_process_exit(cycle); } continue; } if (ev == WAIT_TIMEOUT) { ngx_terminate_worker_processes(cycle); ngx_master_process_exit(cycle); } if (ev == WAIT_FAILED) { ngx_log_error(NGX_LOG_ALERT, cycle->log, err, "WaitForMultipleObjects() failed"); continue; } ngx_log_error(NGX_LOG_ALERT, cycle->log, 0, "WaitForMultipleObjects() returned unexpected value %ul", ev); } }
/*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ CurlBlastDlg::CurlBlastDlg(CWnd* pParent /*=NULL*/) : CDialog(CurlBlastDlg::IDD, pParent) , start(0) , freq(0) , firstIdleTime(0) , firstKernelTime(0) , firstUserTime(0) , lastIdleTime(0) , lastKernelTime(0) , lastUserTime(0) , logFile(_T("")) , startupDelay(1000) , computerName(_T("")) , lastUpload(0) , testID(0) , configID(0) , timeout(0) , running(false) , checkOpt(1) , bDrWatson(false) , accountBase(_T("user")) , password(_T("2dialit")) , browserWidth(1024) , browserHeight(768) , debug(0) , urlManager(log) , pipeIn(0) , pipeOut(0) , ec2(0) , useCurrentAccount(0) , hHookDll(NULL) , keepDNS(0) , worker(NULL) , hRunningThread(NULL) , hMustExit(NULL) , lastAlive(0) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); hMustExit = CreateEvent(NULL, TRUE, FALSE, NULL); testingMutex = CreateMutex(NULL, FALSE, _T("Global\\WebPagetest")); InitializeCriticalSection(&cs); // handle crash events crashLog = &log; SetUnhandledExceptionFilter(CrashFilter); // create a NULL DACL we will re-use everywhere we do file access ZeroMemory(&nullDacl, sizeof(nullDacl)); nullDacl.nLength = sizeof(nullDacl); nullDacl.bInheritHandle = FALSE; if( InitializeSecurityDescriptor(&SD, SECURITY_DESCRIPTOR_REVISION) ) if( SetSecurityDescriptorDacl(&SD, TRUE,(PACL)NULL, FALSE) ) nullDacl.lpSecurityDescriptor = &SD; // randomize the random number generator FILETIME ft; GetSystemTimeAsFileTime(&ft); srand(ft.dwLowDateTime); // get the computer name TCHAR buff[MAX_COMPUTERNAME_LENGTH + 1]; DWORD len = _countof(buff); if( GetComputerName(buff, &len) ) computerName = buff; // let our process kill processes from other users HANDLE hToken; if( OpenProcessToken( GetCurrentProcess() , TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY , &hToken) ) { TOKEN_PRIVILEGES tp; if( LookupPrivilegeValue( NULL , SE_DEBUG_NAME, &tp.Privileges[0].Luid ) ) { tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken , FALSE , &tp , 0 , (PTOKEN_PRIVILEGES) 0 , 0 ) ; } CloseHandle(hToken); } }
static int dshow_read_header(AVFormatContext *avctx) { struct dshow_ctx *ctx = avctx->priv_data; IGraphBuilder *graph = NULL; ICreateDevEnum *devenum = NULL; IMediaControl *control = NULL; IMediaEvent *media_event = NULL; HANDLE media_event_handle; HANDLE proc; int ret = AVERROR(EIO); int r; CoInitialize(0); if (!ctx->list_devices && !parse_device_name(avctx)) { av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n"); goto error; } ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id : AV_CODEC_ID_RAWVIDEO; if (ctx->pixel_format != AV_PIX_FMT_NONE) { if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) { av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when " "video codec is not set or set to rawvideo\n"); ret = AVERROR(EINVAL); goto error; } } if (ctx->framerate) { r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate); if (r < 0) { av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate); goto error; } } r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, &IID_IGraphBuilder, (void **) &graph); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n"); goto error; } ctx->graph = graph; r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, &IID_ICreateDevEnum, (void **) &devenum); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n"); goto error; } if (ctx->list_devices) { av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n"); dshow_cycle_devices(avctx, devenum, VideoDevice, NULL); av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n"); dshow_cycle_devices(avctx, devenum, AudioDevice, NULL); ret = AVERROR_EXIT; goto error; } if (ctx->list_options) { if (ctx->device_name[VideoDevice]) dshow_list_device_options(avctx, devenum, VideoDevice); if (ctx->device_name[AudioDevice]) dshow_list_device_options(avctx, devenum, AudioDevice); ret = AVERROR_EXIT; goto error; } if (ctx->device_name[VideoDevice]) { if ((r = dshow_open_device(avctx, devenum, VideoDevice)) < 0 || (r = dshow_add_device(avctx, VideoDevice)) < 0) { ret = r; goto error; } } if (ctx->device_name[AudioDevice]) { if ((r = dshow_open_device(avctx, devenum, AudioDevice)) < 0 || (r = dshow_add_device(avctx, AudioDevice)) < 0) { ret = r; goto error; } } ctx->mutex = CreateMutex(NULL, 0, NULL); if (!ctx->mutex) { av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n"); goto error; } ctx->event[1] = CreateEvent(NULL, 1, 0, NULL); if (!ctx->event[1]) { av_log(avctx, AV_LOG_ERROR, "Could not create Event\n"); goto error; } r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n"); goto error; } ctx->control = control; r = IGraphBuilder_QueryInterface(graph, &IID_IMediaEvent, (void **) &media_event); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not get media event.\n"); goto error; } ctx->media_event = media_event; r = IMediaEvent_GetEventHandle(media_event, (void *) &media_event_handle); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not get media event handle.\n"); goto error; } proc = GetCurrentProcess(); r = DuplicateHandle(proc, media_event_handle, proc, &ctx->event[0], 0, 0, DUPLICATE_SAME_ACCESS); if (!r) { av_log(avctx, AV_LOG_ERROR, "Could not duplicate media event handle.\n"); goto error; } r = IMediaControl_Run(control); if (r == S_FALSE) { OAFilterState pfs; r = IMediaControl_GetState(control, 0, &pfs); } if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not run filter\n"); goto error; } ret = 0; error: if (devenum) ICreateDevEnum_Release(devenum); if (ret < 0) dshow_read_close(avctx); return ret; }
zt_module::zt_module(int t,int b) { statusstr=NULL; tpb = t; bpm = b; hEditMutex = CreateMutex(NULL, FALSE, TEXT("EditLock")); init(); }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine, int nCmdShow) { MSG Msg; HWND hWnd; WNDCLASS wndclass; int tmp = 0; DisableAutorun(); //CreateMutexEx(NULL, L"KillAutorunMutex", CREATE_MUTEX_INITIAL_OWNER, MUTEX_ALL_ACCESS); CreateMutex(NULL, TRUE, TEXT("KillAutorunMutex")); tmp = GetLastError(); if(tmp == ERROR_ALREADY_EXISTS) return 0; hIcon = static_cast<HICON>(LoadImage(hInstance, MAKEINTRESOURCE(MAINICON), IMAGE_ICON, 16, 16, LR_DEFAULTSIZE)); hinstance = hInstance; static TCHAR szAppName[] = TEXT ("KillAutorun") ; wndclass.style = CS_HREDRAW | CS_VREDRAW ; wndclass.lpfnWndProc = WndProc ; wndclass.cbClsExtra = 0 ; wndclass.cbWndExtra = 0 ; wndclass.hInstance = hInstance ; wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ; wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ; wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ; wndclass.lpszMenuName = NULL ; wndclass.lpszClassName = szAppName ; if (!RegisterClass (&wndclass)) { MessageBox (NULL, TEXT ("This program requires Windows NT!"), szAppName, MB_ICONERROR); return 0 ; } hWnd = CreateWindow(szAppName, TEXT(""), WS_BORDER, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_MESSAGE, NULL, hInstance, NULL); nib.cbSize = sizeof(NOTIFYICONDATA); nib.hIcon = hIcon; nib.hWnd = hWnd; nib.uID = 1; nib.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE; tmp = _tcslen(szAppName)+1; _tcscpy_s(nib.szTip, tmp, szAppName); nib.uCallbackMessage = WM_USER_NIC; nib.uVersion = NOTIFYICON_VERSION; Shell_NotifyIcon(NIM_ADD, &nib); //WorstCaseCleanAutorunX(); if(hDlg == NULL) hDlg = CreateDialog(hinstance, MAKEINTRESOURCE(IDD_DIALOG1), 0, reinterpret_cast<DLGPROC>(DlgProc)); //ShowWindow(hDlg, SW_SHOW); while( GetMessage(&Msg, NULL, 0, 0) ) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return 0; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, LPSTR CmdLine, int CmdShow) { #ifdef _debug CreateConsole(); printf("%s%d%s","DEBUG BUILD ", IDI_APPLICATION,"\n"); hMutex = CreateMutex(NULL,FALSE,NULL); if(hMutex == NULL) { printf("Cannot create Mutex: %d\n",GetLastError()); } #endif INFO("Initialisierung.."); INFO("Registriere Hauptfenster..."); InitCommonControls(); WNDCLASSEX wc; HWND hwnd; MSG Msg; // Fenster registrieren wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(MAINICON)); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH) COLOR_BACKGROUND+1; wc.lpszClassName = g_szClassName; wc.lpszMenuName = MAKEINTRESOURCE(IDR_MENU); wc.hIconSm = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(MAINICON)); if(!RegisterClassEx(&wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 1; } // Schritt 2: Fenster erstellen: hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, g_szClassName, "I-Calculator", WS_SYSMENU | WS_MINIMIZEBOX, CW_USEDEFAULT,CW_USEDEFAULT, 640,420, NULL,NULL,hInstance, NULL); if(hwnd == NULL) { MessageBox(NULL, "Window Creation failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 1; } // Working Thread erstellen MainWindowHwnd = hwnd; INFO("Erstelle Worker Thread..."); hEvent = CreateEvent(NULL,FALSE,FALSE,NULL); HANDLE thread = CreateThread(NULL,16000,&MainWorkingThread,&hEvent,(DWORD)0,&ThreadIds[0]); WaitForSingleObject(hEvent,INFINITE); INFO("Sende Nachricht an Thread..."); if(PostThreadMessage(ThreadIds[0],TH_PYTHON_START,0x0,0x0) == FALSE) { if(GetLastError() == ERROR_INVALID_THREAD_ID) { ERR("Nachricht konnte nicht gesendet werden, falsche Thread Id!"); } else { ERR("Nachricht konnte nicht gesendet werden!"); } } INFO("Springe in die Nachrichten-Schleife..."); INFO("Fertig!"); ShowWindow(hwnd,CmdShow); UpdateWindow(hwnd); // Schritt 3: Main Loop while(GetMessage(&Msg,NULL,0,0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } return Msg.wParam; }
BOOL CschedulerDlg::OnInitDialog() { CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here //mutex m_mutex = OpenMutex(MUTEX_ALL_ACCESS ,FALSE,_T("herb")); if (m_mutex==0) { CreateMutex(NULL,FALSE,_T("herb")); } else { EndDialog(1); return 0; } m_app=AfxGetApp(); //set min size CRect temprect(0,0,300,200); setMinRect(temprect); m_pData=(ITEMDATA**)calloc(KS_MAX_ITIMES,sizeof(ITEMDATA*)); for(int i=0;i<KS_MAX_ITIMES;i++) m_pData[i]=0; m_now.SetFormat(_T("dd HH:mm:ss")); m_list.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_FULLROWSELECT); m_hours.SetFormat(_T("HH:mm:ss")); COleDateTime mytime; /*mytime.Format(_T("dd HH:MM"));*/ mytime.SetTime(0,0,0); m_hours.SetTime(mytime); //m_list.InsertColumn(0,_T("Time"),0,LVCF_DEFAULTWIDTH); m_list.InsertColumn(1,_T("Sub"),0,LVCF_DEFAULTWIDTH); m_list.InsertColumn(2,_T("Note"),0,LVCF_DEFAULTWIDTH); m_list.InsertColumn(0,_T("Date"),0,LVCF_DEFAULTWIDTH); SetTimer(1,KS_DELAY,0); SetTimer(2,1000,0); SetTimer(3,KS_STORE_TIMER,0); m_timeSyn=m_app->GetProfileInt(_T("KScheduler"),_T("update_time"),0); m_nowChk.SetCheck(m_timeSyn); restoreNote(); updatePosition(KS_SETPOS); updateSetting(); return TRUE; // return TRUE unless you set the focus to a control }
CMainWindow::CMainWindow(CPS2VM& virtualMachine, char* cmdLine) : m_virtualMachine(virtualMachine) , m_recordingAvi(false) , m_recordBuffer(nullptr) , m_recordBufferWidth(0) , m_recordBufferHeight(0) , m_recordAviMutex(NULL) , m_frames(0) , m_drawCallCount(0) , m_stateSlot(0) , m_outputWnd(nullptr) , m_statusBar(nullptr) , m_accTable(NULL) { m_recordAviMutex = CreateMutex(NULL, FALSE, NULL); TCHAR sVersion[256]; CAppConfig::GetInstance().RegisterPreferenceBoolean(PREF_UI_PAUSEWHENFOCUSLOST, true); if(!DoesWindowClassExist(CLSNAME)) { WNDCLASSEX wc; memset(&wc, 0, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW); wc.hInstance = GetModuleHandle(NULL); wc.lpszClassName = CLSNAME; wc.lpfnWndProc = CWindow::WndProc; wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; RegisterClassEx(&wc); } Create(NULL, CLSNAME, _T(""), WNDSTYLE, Framework::Win32::CRect(0, 0, 640, 480), NULL, NULL); SetClassPtr(); #ifdef DEBUGGER_INCLUDED CDebugger::InitializeConsole(); #endif m_virtualMachine.Initialize(); SetIcon(ICON_SMALL, LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PUREI))); SetIcon(ICON_BIG, LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_PUREI))); SetMenu(LoadMenu(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_MAINWINDOW))); #ifdef DEBUGGER_INCLUDED m_debugger = std::unique_ptr<CDebugger>(new CDebugger(m_virtualMachine)); m_frameDebugger = std::unique_ptr<CFrameDebugger>(new CFrameDebugger()); CreateDebugMenu(); #endif PrintVersion(sVersion, countof(sVersion)); m_outputWnd = new COutputWnd(m_hWnd); m_statusBar = new Framework::Win32::CStatusBar(m_hWnd); m_statusBar->SetParts(2, m_statusBarPanelWidths); m_statusBar->SetText(STATUSPANEL, sVersion); m_statusBar->SetText(FPSPANEL, _T("")); //m_virtualMachine.CreateGSHandler(CGSH_Null::GetFactoryFunction()); m_virtualMachine.CreateGSHandler(CGSH_OpenGLWin32::GetFactoryFunction(m_outputWnd)); m_virtualMachine.CreatePadHandler(CPH_DirectInput::GetFactoryFunction(m_hWnd)); m_deactivatePause = false; m_pauseFocusLost = CAppConfig::GetInstance().GetPreferenceBoolean(PREF_UI_PAUSEWHENFOCUSLOST); m_virtualMachine.m_gs->OnNewFrame.connect(boost::bind(&CMainWindow::OnNewFrame, this, _1)); SetTimer(m_hWnd, NULL, 1000, NULL); //Initialize status bar OnTimer(0); m_virtualMachine.m_os->OnExecutableChange.connect(boost::bind(&CMainWindow::OnExecutableChange, this)); CreateStateSlotMenu(); CreateAccelerators(); if(strstr(cmdLine, "--cdrom0") != nullptr) { BootCDROM(); } #ifdef DEBUGGER_INCLUDED if(strstr(cmdLine, "--debugger") != nullptr) { ShowDebugger(); } if(strstr(cmdLine, "--framedebugger") != nullptr) { ShowFrameDebugger(); } #endif RefreshLayout(); UpdateUI(); Center(); Show(SW_SHOW); }
void mainLoader(int argc, char* argv[], ServiceManager* services) { //dispatcher thread g_game.setGameState(GAME_STATE_STARTUP); srand((unsigned int)OTSYS_TIME()); #ifdef _WIN32 SetConsoleTitle(STATUS_SERVER_NAME); #endif std::cout << STATUS_SERVER_NAME << " - Version " << STATUS_SERVER_VERSION << std::endl; std::cout << "Compilied on " << __DATE__ << ' ' << __TIME__ << " for arch "; #if defined(__amd64__) || defined(_M_X64) std::cout << "x64" << std::endl; #elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) std::cout << "x86" << std::endl; #elif defined(__arm__) std::cout << "ARM" << std::endl; #elif defined(__mips__) std::cout << "MIPS" << std::endl; #else std::cout << "unk" << std::endl; #endif std::cout << std::endl; std::cout << "A server developed by " << STATUS_SERVER_DEVELOPERS << std::endl; std::cout << "Visit our forum for updates, support, and resources: http://otland.net/." << std::endl; std::cout << std::endl; // read global config std::cout << ">> Loading config" << std::endl; if (!g_config.load()) { startupErrorMessage("Unable to load config.lua!"); return; } #ifdef _WIN32 std::string defaultPriority = asLowerCaseString(g_config.getString(ConfigManager::DEFAULT_PRIORITY)); if (defaultPriority == "realtime") { SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); } else if (defaultPriority == "high") { SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); } else if (defaultPriority == "higher") { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); } std::ostringstream mutexName; mutexName << "forgottenserver_" << g_config.getNumber(ConfigManager::LOGIN_PORT); CreateMutex(nullptr, FALSE, mutexName.str().c_str()); if (GetLastError() == ERROR_ALREADY_EXISTS) { startupErrorMessage("Another instance of The Forgotten Server is already running with the same login port, please shut it down first or change ports for this one."); return; } #endif #ifdef __PROTOCOL_77__ //set RSA key const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113"); const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101"); g_RSA.setKey(p, q); #endif std::cout << ">> Establishing database connection..." << std::flush; Database* db = Database::getInstance(); if (!db->connect()) { startupErrorMessage("Failed to connect to database."); return; } std::cout << " MySQL " << db->getClientVersion() << std::endl; // run database manager std::cout << ">> Running database manager" << std::endl; DatabaseManager* dbManager = DatabaseManager::getInstance(); if (!dbManager->isDatabaseSetup()) { startupErrorMessage("The database you have specified in config.lua is empty, please import the schema to the database."); return; } dbManager->updateDatabase(); dbManager->checkTriggers(); dbManager->checkEncryption(); if (g_config.getBoolean(ConfigManager::OPTIMIZE_DATABASE) && !dbManager->optimizeTables()) { std::cout << "> No tables were optimized." << std::endl; } //load vocations std::cout << ">> Loading vocations" << std::endl; if (!g_vocations.loadFromXml()) { startupErrorMessage("Unable to load vocations!"); return; } //load commands std::cout << ">> Loading commands" << std::endl; if (!g_commands.loadFromXml()) { startupErrorMessage("Unable to load commands!"); return; } // load item data std::cout << ">> Loading items" << std::endl; if (Item::items.loadFromOtb("data/items/" + ITEMS_PATH + "/items.otb")) { startupErrorMessage("Unable to load items (OTB)!"); return; } if (!Item::items.loadFromXml()) { startupErrorMessage("Unable to load items (XML)!"); return; } std::cout << ">> Loading script systems" << std::endl; if (!ScriptingManager::getInstance()->loadScriptSystems()) { startupErrorMessage("Failed to load script systems"); return; } std::cout << ">> Loading monsters" << std::endl; if (!g_monsters.loadFromXml()) { startupErrorMessage("Unable to load monsters!"); return; } std::cout << ">> Loading experience stages" << std::endl; if (!g_game.loadExperienceStages()) { startupErrorMessage("Unable to load experience stages!"); return; } std::string passwordType = asLowerCaseString(g_config.getString(ConfigManager::PASSWORDTYPE)); if (passwordType == "sha1") { g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_SHA1); std::cout << ">> Using SHA1 passwords" << std::endl; } else { g_config.setNumber(ConfigManager::PASSWORD_TYPE, PASSWORD_TYPE_PLAIN); std::cout << ">> Using plaintext passwords" << std::endl; } std::cout << ">> Checking world type... " << std::flush; std::string worldType = asLowerCaseString(g_config.getString(ConfigManager::WORLD_TYPE)); if (worldType == "pvp") { g_game.setWorldType(WORLD_TYPE_PVP); } else if (worldType == "no-pvp") { g_game.setWorldType(WORLD_TYPE_NO_PVP); } else if (worldType == "pvp-enforced") { g_game.setWorldType(WORLD_TYPE_PVP_ENFORCED); } else { std::cout << std::endl; std::ostringstream ss; ss << "> ERROR: Unknown world type: " << g_config.getString(ConfigManager::WORLD_TYPE) << ", valid world types are: pvp, no-pvp and pvp-enforced."; startupErrorMessage(ss.str()); return; } std::cout << asUpperCaseString(worldType) << std::endl; std::cout << ">> Loading map" << std::endl; if (!g_game.loadMap(g_config.getString(ConfigManager::MAP_NAME))) { startupErrorMessage("Failed to load map"); return; } std::cout << ">> Initializing gamestate" << std::endl; g_game.setGameState(GAME_STATE_INIT); // Tibia protocols services->add<ProtocolGame>(g_config.getNumber(ConfigManager::GAME_PORT)); services->add<ProtocolLogin>(g_config.getNumber(ConfigManager::LOGIN_PORT)); // OT protocols services->add<ProtocolStatus>(g_config.getNumber(ConfigManager::STATUS_PORT)); int32_t autoSaveEachMinutes = g_config.getNumber(ConfigManager::AUTO_SAVE_EACH_MINUTES); if (autoSaveEachMinutes > 0) { g_scheduler.addEvent(createSchedulerTask(autoSaveEachMinutes * 1000 * 60, boost::bind(&Game::autoSave, &g_game))); } if (g_config.getBoolean(ConfigManager::SERVERSAVE_ENABLED)) { int32_t serverSaveHour = g_config.getNumber(ConfigManager::SERVERSAVE_H); if (serverSaveHour >= 0 && serverSaveHour <= 24) { time_t timeNow = time(nullptr); tm* timeinfo = localtime(&timeNow); if (serverSaveHour == 0) { serverSaveHour = 23; } else { serverSaveHour--; } timeinfo->tm_hour = serverSaveHour; timeinfo->tm_min = 55; timeinfo->tm_sec = 0; double difference = difftime(mktime(timeinfo), timeNow); if (difference < 0) { difference += 86400; } g_scheduler.addEvent(createSchedulerTask(difference * 1000, boost::bind(&Game::prepareServerSave, &g_game))); } } Houses::getInstance().payHouses(); IOLoginData::getInstance()->updateHouseOwners(); g_npcs.reload(); std::cout << ">> Loaded all modules, server starting up..." << std::endl; std::pair<uint32_t, uint32_t> IpNetMask; IpNetMask.first = inet_addr("127.0.0.1"); IpNetMask.second = 0xFFFFFFFF; serverIPs.push_back(IpNetMask); char szHostName[128]; if (gethostname(szHostName, 128) == 0) { hostent* he = gethostbyname(szHostName); if (he) { unsigned char** addr = (unsigned char**)he->h_addr_list; while (addr[0] != nullptr) { IpNetMask.first = *(uint32_t*)(*addr); IpNetMask.second = 0xFFFFFFFF; serverIPs.push_back(IpNetMask); addr++; } } } std::string ip = g_config.getString(ConfigManager::IP); uint32_t resolvedIp = inet_addr(ip.c_str()); if (resolvedIp == INADDR_NONE) { struct hostent* he = gethostbyname(ip.c_str()); if (!he) { std::ostringstream ss; ss << "ERROR: Cannot resolve " << ip << "!" << std::endl; startupErrorMessage(ss.str()); return; } resolvedIp = *(uint32_t*)he->h_addr; } IpNetMask.first = resolvedIp; IpNetMask.second = 0; serverIPs.push_back(IpNetMask); #if !defined(WIN32) && !defined(__ROOT_PERMISSION__) if (getuid() == 0 || geteuid() == 0) { std::cout << "> WARNING: " << STATUS_SERVER_NAME << " has been executed as root user, it is recommended to execute is as a normal user." << std::endl; } #endif g_game.start(services); g_game.setGameState(GAME_STATE_NORMAL); g_loaderSignal.notify_all(); }
/** * Main function */ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { /* Do not use a global namespace ("Global\\") for mutex name here, will blow up NT4 compatibility! */ HANDLE hMutexAppRunning = CreateMutex(NULL, FALSE, "VBoxTray"); if ( hMutexAppRunning != NULL && GetLastError() == ERROR_ALREADY_EXISTS) { /* Close the mutex for this application instance. */ CloseHandle (hMutexAppRunning); hMutexAppRunning = NULL; return 0; } LogRel(("VBoxTray: %s r%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr())); int rc = RTR3InitExeNoArguments(0); if (RT_SUCCESS(rc)) { rc = VbglR3Init(); if (RT_SUCCESS(rc)) rc = vboxTrayOpenBaseDriver(); } if (RT_SUCCESS(rc)) { /* Save instance handle. */ ghInstance = hInstance; hlpReportStatus(VBoxGuestFacilityStatus_Init); rc = vboxTrayCreateToolWindow(); if (RT_SUCCESS(rc)) { rc = vboxTraySetupSeamless(); if (RT_SUCCESS(rc)) { Log(("VBoxTray: Init successful\n")); rc = vboxTrayServiceMain(); if (RT_SUCCESS(rc)) hlpReportStatus(VBoxGuestFacilityStatus_Terminating); vboxTrayShutdownSeamless(); } vboxTrayDestroyToolWindow(); } if (RT_SUCCESS(rc)) hlpReportStatus(VBoxGuestFacilityStatus_Terminated); } if (RT_FAILURE(rc)) { LogRel(("VBoxTray: Error while starting, rc=%Rrc\n", rc)); hlpReportStatus(VBoxGuestFacilityStatus_Failed); } LogRel(("VBoxTray: Ended\n")); vboxTrayCloseBaseDriver(); /* Release instance mutex. */ if (hMutexAppRunning != NULL) { CloseHandle(hMutexAppRunning); hMutexAppRunning = NULL; } VbglR3Term(); return RT_SUCCESS(rc) ? 0 : 1; }
int SSQ_Init(SS_QUEUE_OBJ_T *pObj, unsigned int sharememory, unsigned int channelid, wchar_t *sharename, unsigned int bufsize, unsigned int prerecordsecs, unsigned int createsharememory) { wchar_t wszHeaderName[36] = {0,}; wchar_t wszFramelistName[36] = {0,}; wchar_t wszDataName[36] = {0,}; if (NULL==pObj) return -1; if (createsharememory==0x01 && bufsize<1) return -1; if ( (sharememory==0x01) && (NULL==sharename || (0==wcscmp(sharename, TEXT("\0")))) ) return -1; memset(pObj, 0x00, sizeof(SS_QUEUE_OBJ_T)); pObj->channelid = channelid; pObj->shareinfo.id = channelid; wcscpy(pObj->shareinfo.name, sharename); wchar_t wszMutexName[36] = {0,}; wsprintf(wszMutexName, TEXT("%s%d_mutex"), sharename, channelid); pObj->hMutex = OpenMutex(NULL, FALSE, wszMutexName); if (NULL == pObj->hMutex) { pObj->hMutex = CreateMutex(NULL, FALSE, wszMutexName); if (NULL == pObj->hMutex) return -1; } //Create Header map #ifdef _WIN32 if (sharememory == 0x01) { wsprintf(wszHeaderName, TEXT("%s%d_h"), sharename, channelid); pObj->hSSHeader = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszHeaderName); if (NULL==pObj->hSSHeader && createsharememory==0x01) { pObj->hSSHeader = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, sizeof(SS_HEADER_T), wszHeaderName); if (NULL==pObj->hSSHeader || pObj->hSSHeader==INVALID_HANDLE_VALUE) { return -1; } } pObj->pQueHeader = (SS_HEADER_T*)MapViewOfFile(pObj->hSSHeader, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0); if (createsharememory==0x01) { if (pObj->pQueHeader->bufsize < 1) { memset(pObj->pQueHeader, 0x00, sizeof(SS_HEADER_T)); pObj->pQueHeader->bufsize = bufsize; } } else if (NULL==pObj->pQueHeader) { return -1; } else { bufsize = pObj->pQueHeader->bufsize; } } else { pObj->pQueHeader = new SS_HEADER_T; memset(pObj->pQueHeader, 0x00, sizeof(SS_HEADER_T)); } //========================================== //Create frame list map if (prerecordsecs > 0) { wsprintf(wszFramelistName, TEXT("%s%d_f"), sharename, channelid); unsigned int nFramelistNum = prerecordsecs * 30; //每秒30帧 unsigned int nFrameQueSize = nFramelistNum*sizeof(FRAMEINFO_LIST_T); if (sharememory == 0x01) { pObj->hSSFrameList = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszFramelistName); if (NULL==pObj->hSSFrameList && createsharememory==0x01) { pObj->hSSFrameList = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, nFrameQueSize, wszFramelistName); if (NULL==pObj->hSSFrameList || pObj->hSSFrameList==INVALID_HANDLE_VALUE) { return -1; } } pObj->pFrameinfoList = (FRAMEINFO_LIST_T*)MapViewOfFile(pObj->hSSFrameList, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0); if (createsharememory==0x01) { memset(pObj->pFrameinfoList, 0x00, nFrameQueSize); pObj->pQueHeader->framelistNum = nFramelistNum; } else if (NULL==pObj->hSSFrameList) { return -1; } } else { pObj->pFrameinfoList = new FRAMEINFO_LIST_T[nFramelistNum]; memset(&pObj->pFrameinfoList[0], 0x00, sizeof(FRAMEINFO_LIST_T)*nFramelistNum); pObj->pQueHeader->framelistNum = nFramelistNum; } } //Create data map if (sharememory == 0x01) { wsprintf(wszDataName, TEXT("%s%d_b"), sharename, channelid); pObj->hSSData = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, wszDataName); if (NULL==pObj->hSSData && createsharememory==0x01) { pObj->hSSData = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE|SEC_COMMIT, 0, bufsize, wszDataName); } if (NULL == pObj->hSSData || pObj->hSSData==INVALID_HANDLE_VALUE) { return -1; } pObj->pQueData = (char*)MapViewOfFile(pObj->hSSData, FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, 0); } else { pObj->pQueData = new char [bufsize]; pObj->pQueHeader->bufsize = bufsize; } if (createsharememory==0x01) { //memset(pQueHeader, 0x00, sizeof(SS_HEADER_T)); memset(pObj->pQueData, 0x00, bufsize); } #else int ret = shm_create((SYNC_VID_SHM_KEY<<8)|channelid, &pObj->shmHdrid, sizeof(SS_HEADER_T), (char**)&pObj->pQueHeader); if (ret < 0) { return -1; } SSQ_TRACE("[%d]pQueHeader: %d\n", (SYNC_VID_SHM_KEY<<8)|channelid, pObj->shmHdrid); ret = shm_create((SYNC_VID_SHM_KEY<<16)|channelid, &pObj->shmDatid, bufsize, (char**)&pObj->pQueData); if (ret < 0) { shm_delete(&pObj->shmHdrid, (char*)pObj->pQueHeader); return -1; } pObj->pQueHeader->bufsize = bufsize; SSQ_TRACE("[%d]pQueData: %d\n", (SYNC_VID_SHM_KEY<<16)|channelid, pObj->shmDatid); #endif return 0; }
EXTERN_C_BEGIN #undef __FUNCT__ #define __FUNCT__ "PetscDrawCreate_Win32" PetscErrorCode PetscDrawCreate_Win32(PetscDraw draw) { PetscDraw_Win32 *windraw; HANDLE hThread = NULL; PetscErrorCode ierr; WindowNode newnode; PetscFunctionBegin; ierr = PetscNew(PetscDraw_Win32,&windraw);CHKERRQ(ierr); draw->data = windraw; /* the following is temporary fix for initializing a global datastructure */ if(!g_hWindowListMutex) { g_hWindowListMutex = CreateMutex(NULL,FALSE,NULL); } ierr = PetscMemcpy(draw->ops,&DvOps,sizeof(DvOps));CHKERRQ(ierr); windraw->hReadyEvent = CreateEvent(NULL,TRUE,FALSE,NULL); /* makes call to MessageLoopThread to creat window and attach a thread */ CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)MessageLoopThread_Win32,draw,0,(unsigned long*)hThread); CloseHandle(hThread); WaitForSingleObject(windraw->hReadyEvent,INFINITE); CloseHandle(windraw->hReadyEvent); WaitForSingleObject(g_hWindowListMutex,INFINITE); ierr = PetscNew(struct _p_WindowNode,&newnode);CHKERRQ(ierr); newnode->MouseListHead = NULL; newnode->MouseListTail = NULL; newnode->wnext = WindowListHead; newnode->wprev = NULL; newnode->hWnd = windraw->hWnd; if(WindowListHead != NULL) { WindowListHead->wprev = newnode; } WindowListHead = newnode; windraw->hdc = GetDC(windraw->hWnd); windraw->stringheight = 10; windraw->stringwidth = 6; windraw->linewidth = 1; /* default pixel sizes of graphics until user changes them */ windraw->pointdiameter = 1; windraw->node = newnode; windraw->x = draw->x; windraw->y = draw->y; windraw->w = newnode->bitwidth = draw->w; windraw->h = newnode->bitheight = draw->h; /* Create and initialize primary graphics buffer */ newnode->Buffer = CreateCompatibleDC(windraw->hdc); newnode->BufferBit = CreateCompatibleBitmap(windraw->hdc,windraw->w,windraw->h); newnode->store = SelectObject(newnode->Buffer,newnode->BufferBit); ExtFloodFill(newnode->Buffer,0,0,COLOR_WINDOW,FLOODFILLBORDER); newnode->event = CreateEvent(NULL,TRUE,FALSE,NULL); newnode->DoubleBuffered = PETSC_FALSE; ReleaseDC(windraw->hWnd,windraw->hdc); ReleaseMutex(g_hWindowListMutex); PetscFunctionReturn(0); }
/* * !!! FIXME: why aren't we using Critical Sections instead of Mutexes? * !!! FIXME: mutexes on Windows are for cross-process sync. CritSects are * !!! FIXME: mutexes for threads in a single process and are faster. */ void *__PHYSFS_platformCreateMutex(void) { return((void *) CreateMutex(NULL, FALSE, NULL)); } /* __PHYSFS_platformCreateMutex */
/* * Call a blocking function (returning an int) as a modal thread with a progress bar */ int run_with_progress_bar(HWND hWnd, int(*function)(void*), void* arglist) { HWND hDlg; MSG msg; WNDCLASSEX wc; BOOL r; if ( (function == NULL) || (hWnd == NULL) ) { return WDI_ERROR_INVALID_PARAM; } app_instance = (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE); // protect access to the thread variables and prevent 2 progress // dialogs from executing at the same time progress_mutex = CreateMutex(NULL, TRUE, NULL); if ((progress_mutex == NULL) || (GetLastError() == ERROR_ALREADY_EXISTS)) { wdi_err("could not obtain progress dialog mutex - is another dialog active?"); progress_mutex = INVALID_HANDLE_VALUE; return WDI_ERROR_BUSY; } progress_function = function; progress_arglist = arglist; // Since our lib can be static, we can't use resources // => create the whole dialog manually. // First we create Window class if it doesn't already exist if (!GetClassInfoEx(app_instance, TEXT("wdi_progress_class"), &wc)) { wc.cbSize = sizeof(wc); wc.style = CS_DBLCLKS | CS_SAVEBITS; wc.lpfnWndProc = progress_callback; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = app_instance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = TEXT("wdi_progress_class"); wc.lpszMenuName = NULL; wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE); if (!RegisterClassEx(&wc)) { wdi_err("can't register class %s", windows_error_str(0)); safe_closehandle(progress_mutex); return WDI_ERROR_RESOURCE; } } // Then we create the dialog base hDlg = CreateWindowEx(WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT, TEXT("wdi_progress_class"), TEXT("Installing Driver..."), WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_CAPTION | WS_POPUP | WS_VISIBLE | WS_THICKFRAME, 100, 100, 287, 102, hWnd, NULL, app_instance, NULL); if (hDlg == NULL) { wdi_err("Unable to create progress dialog: %s", windows_error_str(0)); safe_closehandle(progress_mutex); return WDI_ERROR_RESOURCE; } // Finally we Display the dialog... ShowWindow(hDlg, SW_SHOWNORMAL); UpdateWindow(hDlg); // ...and handle the message processing loop while( (r = GetMessage(&msg, NULL, 0, 0)) != 0) { if (r == -1) { wdi_err("GetMessage error"); } else { TranslateMessage(&msg); DispatchMessage(&msg); } } safe_closehandle(progress_mutex); return (int)msg.wParam; }
unsigned long ThreadBuscarArchivos::_ThreadBusqueda(void *pThis) { size_t i = 0; ThreadBuscarArchivos *This = reinterpret_cast<ThreadBuscarArchivos *>(pThis); This->_Mutex = CreateMutex(NULL, FALSE, TEXT("Mutex_ThreadBuscarArchivos")); // This->_Buscando = true; DWL::DWLString *TmpStr = NULL; // Inicio la VLC para el analisis DWL::DWLString PluginPath; PluginPath.sprintf(TEXT("--plugin-path=%s%s"), This->_PathApp(), PATHVLC_PLUGINS); ArgumentosVLC ArgsVLC; ArgsVLC.AgregarArgumento(This->_PathApp()); // Path de la aplicación ArgsVLC.AgregarArgumento(PluginPath()); // Path del directorio de plugins libvlc_instance_t *InstanciaVLC = libvlc_new(ArgsVLC.TotalArgumentos(), ArgsVLC()); // Inicio el FMOD para el analisis FMOD::System *InstanciaFMOD; FMOD_RESULT FmodErrorCode = FMOD_OK; FmodErrorCode = FMOD::System_Create(&InstanciaFMOD); // - Obtengo el path de los pluguins DWL::DWLString CodecsPath = This->_PathApp(); CodecsPath += TEXT("Plugins\\FMOD"); // - Paso el path de unicode a ascii char CodecsPathAscii[MAX_PATH + 1] = ""; WideCharToMultiByte(CP_OEMCP, WC_NO_BEST_FIT_CHARS, CodecsPath(), static_cast<int>(CodecsPath.Tam()) + 1, CodecsPathAscii, MAX_PATH + 1, NULL, NULL); FmodErrorCode = InstanciaFMOD->setPluginPath(CodecsPathAscii); // Inicio el sonido con 16 canales FmodErrorCode = InstanciaFMOD->init(16, FMOD_INIT_NORMAL, NULL); // Busco en todas las rutas for (i = 0; i < This->_PathsBuscar.size(); i++) This->_BusquedaRecursiva(This->_PathsBuscar[i].Path()); PostMessage(This->_hWndCP, MENSAJE_OBTENIENDO_DATOS_MEDIOS, static_cast<WPARAM>(This->_PathsEncontrados.size()), NULL); // Ya tengo todos los paths, ahora los escaneamos InformacionArchivoEx *Info = NULL; // libvlc_time_t TiempoTotal; // bool EsVideo; for (i = 0; i < This->_PathsEncontrados.size(); i++) { if (This->_Mutex) WaitForSingleObject(This->_Mutex, INFINITE); // This->_VentanaLog->AgregarMensaje(Log_BubaTronik, Log_Info, "Analizando :", This->_PathsEncontrados[i].Texto()); if (SendMessage(This->_hWndCP, MENSAJE_MEDIO_NO_EXISTE, reinterpret_cast<WPARAM>(This->_PathsEncontrados[i].Texto()), 0) == 1) { SOLO_DEBUG(DWL::DWLDebug::ImprimirDebug(This->_PathsEncontrados[i].Texto())); SOLO_DEBUG(DWL::DWLDebug::ImprimirDebug(TEXT("\n"))); Info = new InformacionArchivoEx; TmpStr = new DWL::DWLString(This->_PathsEncontrados[i].Texto()); PostMessage(This->_hWndCP, MENSAJE_MEDIO_ANALIZANDO, reinterpret_cast<WPARAM>(TmpStr), NULL); TMedio *TM = Info->ObtenerInfo(This->_PathsEncontrados[i].Texto(), This->_TipoArchivo, This->_Unidades, This->_PathsBuscar, InstanciaVLC, InstanciaFMOD); if (TM != NULL) PostMessage(This->_hWndCP, MENSAJE_MEDIO_ANALIZADO, reinterpret_cast<WPARAM>(TM), NULL); else PostMessage(This->_hWndCP, MENSAJE_MEDIO_INVALIDO, reinterpret_cast<WPARAM>(TM), NULL); delete Info; } if (This->_Cancelar == true) { if (This->_Mutex) ReleaseMutex(This->_Mutex); break; } if (This->_Mutex) ReleaseMutex(This->_Mutex); } // ReleaseMutex(This->_Mutex); // Termino la instancia de la VLC libvlc_release(InstanciaVLC); // Termino la instancia del FMOD InstanciaFMOD->close(); InstanciaFMOD->release(); // Cierro el mutex, y informo a la ventana del reproductor que ya se ha terminado if (This->_Mutex) CloseHandle(This->_Mutex); This->_Mutex = NULL; PostMessage(This->_hWndCP, MENSAJE_BUSCAR_ARCHIVOS_TERMINADO, NULL, NULL); // MessageBox(NULL, TEXT("Terminado"), TEXT("Terminado"), MB_OK); return 0; }
#include "stdafx.h" #include "CUser.h" CUser* CUser::instance; HANDLE CUser::hMutex = CreateMutex(NULL, FALSE, NULL); int CUser::insertUser(unsigned int _userNo, char _userId[USER_ID_MAX_LEN], char _userMacAddr[MAC_ADDR_LEN], SOCKET clientSocket) { struct UserSession session; session.userNo = _userNo; strcpy_s(session.userId,_userId); strcpy_s(session.userMacAddr, _userMacAddr); memset(&session.clientSocket, clientSocket, sizeof(session.clientSocket)); m_sessionVector.push_back(session); //cout << _userId << " / " << _userNo << endl; COutputUtil::getInstance()->ShowLog("技记","历厘 己傍"); return (int)SUCCESS; } void CUser::deleteUser(unsigned int _userNo, char _userMacAddr[MAC_ADDR_LEN]) { for (m_iter = m_sessionVector.begin(); m_iter != m_sessionVector.end(); m_iter++) { if (m_iter->userNo == _userNo && m_iter->userMacAddr == _userMacAddr) { m_sessionVector.erase(m_iter);
BOOL CALLBACK DeleteItemProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_ACTIVATE: CheckDlgButton(hwndDlg, IDC_SYNC, SyncSpeed); CheckDlgButton(hwndDlg, IDC_REVERSE_STEREO, ReverseStereo); break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: // if (!GetDlgItemText(hwndDlg, ID_ITEMNAME, // szItemName, 80)) // *szItemName=0; // Fall through. case IDCANCEL: EndDialog(hwndDlg, wParam); DestroyWindow(hWndConfig); hWndConfig = NULL; return TRUE; case IDC_ABOUT: DllAbout(AudioInfo.hwnd); break; } break; case WM_NOTIFY: switch(LOWORD(wParam)) { case IDC_SYNC: if( SyncSpeed != ( SendDlgItemMessage( hwndDlg, IDC_SYNC, BM_GETCHECK, 0, 0) == BST_CHECKED)) { int TempgUcode = gUcode; InitializeCriticalSection(&CriticalSection); SyncSpeed = ( SendDlgItemMessage( hwndDlg, IDC_SYNC, BM_GETCHECK, 0, 0) == BST_CHECKED); EnterCriticalSection(&CriticalSection); RomClosed(); gUcode = TempgUcode; LeaveCriticalSection(&CriticalSection); DeleteCriticalSection(&CriticalSection); // REGISTRY_WriteDWORD( "AutoFullScreen", emuoptions.auto_full_screen); } break; case IDC_REVERSE_STEREO: if( ReverseStereo != ( SendDlgItemMessage( hwndDlg, IDC_REVERSE_STEREO, BM_GETCHECK, 0, 0) == BST_CHECKED)) { HANDLE hMutex = CreateMutex(NULL,FALSE,NULL); WaitForSingleObject (hMutex, INFINITE); ReverseStereo = ( SendDlgItemMessage( hwndDlg, IDC_REVERSE_STEREO, BM_GETCHECK, 0, 0) == BST_CHECKED); ReleaseMutex(hMutex); // REGISTRY_WriteDWORD( "AutoFullScreen", emuoptions.auto_full_screen); } break; } break; } return FALSE; }