/****************************************************************\ * Routine to start Auto mode. * *--------------------------------------------------------------* * * * Name: SetAutoMode(VOID) * * * * Purpose: Creates thread and semaphore needed to run auto * * mode. * * * * Usage: Called in file usercmd.c when the user selects * * Auto from the semaphore menu. * * * * Returns: NO_ERROR on success, else error from api call. * * * \****************************************************************/ ULONG SetAutoMode() { ULONG rc; rc = DosCreateEventSem((PSZ)NULL,&hevStopAuto,0L,FALSE); if (rc) { SemError("DosCreateEventSem",rc); return(rc); } rc = DosCreateThread((PTID)&tidAutoThread,(PFNTHREAD)RunAuto,0L,0L,STACKSIZE); if (rc) { DosCloseEventSem (hevStopAuto); /* close semaphore created above */ SemError("DosCreateThread", rc); return(rc); } return(NO_ERROR); }
VOID _System threadMouMovMgr(ULONG ul) { ULONG ulPost; POINTL ptl; INT i; ULONG covrd; // numero corrente spostamenti mouse da traiettoria impostata ULONG cstops; // numero di movimenti volontari mouse necessari per // cancellare movimento automatico if (DosCreateEventSem(NULL, &g.mou.hev, DC_SEM_SHARED, 0)) { stlrlog(IDERR_CREATESERVEVSEM); return; } /* endif */ DosSetPriority(PRTYS_THREAD, PRTYC_TIMECRITICAL, 31, 0); for (;;) { restart: // label su cui punta quando esce dal loop interno g.is.mousebtn &= ~MOVEMOUPTR; covrd = 0; DosWaitEventSem(g.mou.hev, SEM_INDEFINITE_WAIT); cstops = (o.mou.moveSteps & 0x2f) >> 3; for (i = 0; i < o.mou.moveSteps; ++i) { WinQueryPointerPos(HWND_DESKTOP, &ptl); // se il mouse Š stato spostato dall'utente x 3 volte if (memcmp(&ptl, &g.mou.ptc, sizeof(POINTL)) && ++covrd > cstops) break; g.mou.wr.cx += g.mou.dp.x; g.mou.wr.cy += g.mou.dp.y; g.mou.ptc.x = (LONG)(g.mou.wr.cx >> 16); g.mou.ptc.y = (LONG)(g.mou.wr.cy >> 16); WinSetPointerPos(HWND_DESKTOP, g.mou.ptc.x, g.mou.ptc.y); DosSleep(1); // se semaforo Š stato resettato perch‚ il puntatore del mouse deve // essere spostato su una finestra differente ricomincia dall'inizio DosQueryEventSem(g.mou.hev, &ulPost); if (!ulPost) goto restart; } /* endfor */ DosResetEventSem(g.mou.hev, &ulPost); g.mou.hwndNew = g.mou.hwnd = NULLHANDLE; } /* endfor */ DosCloseEventSem(g.mou.hev); }
Event::Event ( char *tag, char *Name, int OneInstanceOnly ) : Tag(0), DebugFlag(FALSE) { if ( tag ) { Tag = (char*) malloc ( strlen(tag) + 1 ) ; strcpy ( Tag, tag ) ; } /* endif */ #ifdef __OS2__ char FullName [_MAX_PATH] ; strcpy ( FullName, "\\SEM32\\" ) ; strcat ( FullName, Name?Name:"" ) ; unsigned long Status = 1 ; Handle = 0 ; if ( Name && !OneInstanceOnly ) Status = DosOpenEventSem ( PSZ(FullName), &Handle ) ; if ( Status ) { Status = DosCreateEventSem ( PSZ(Name?FullName:0), &Handle, DC_SEM_SHARED, FALSE ) ; if ( OneInstanceOnly && ( Status == ERROR_DUPLICATE_NAME ) ) Log ( "Event(%s): Unable to create semaphore for '%s'. Already exists.", Tag?Tag:"", Name?Name:"" ) ; else if ( Status ) Log ( "Event(%s): Unable to create semaphore for '%s'. Status %i.", Tag?Tag:"", Name?Name:"", Status ) ; } /* endif */ #else Handle = CreateEvent ( 0, TRUE, FALSE, Name ) ; if ( Handle && OneInstanceOnly && ( GetLastError() == ERROR_ALREADY_EXISTS ) ) { Log ( "Event(%s): Unable to create event semaphore '%s'. Already exists.", Tag?Tag:"", Name?Name:"" ) ; CloseHandle ( Handle ) ; Handle = 0 ; } else if ( !Handle ) { DWORD Status = GetLastError ( ) ; Log ( "Event(%s): Unable to create event semaphore '%s'. Status %i.", Tag?Tag:"", Name?Name:"", Status ) ; } /* endif */ #endif } /* endmethod */
void omni_thread::common_constructor(void* arg, priority_t pri, int det) { _state = STATE_NEW; _priority = pri; next_id_mutex->lock(); _id = next_id++; next_id_mutex->unlock(); thread_arg = arg; detached = det; // may be altered in start_undetached() APIRET rc = DosCreateEventSem( NULL , &cond_semaphore , 0 , FALSE ); if (rc != 0) throw omni_thread_fatal(rc); cond_next = cond_prev = NULL; cond_waiting = FALSE; handle = NULL; }
void DrvMountDrives( HWND hwnd) { ULONG rc = 0; HEV hev = 0; TID tid; char * pErr = 0; do { rc = DosCreateEventSem( 0, &hev, 0, FALSE); if (rc) ERRMSG( "DosCreateEventSem") tid = _beginthread( DrvMountDrivesThread, 0, 0x4000, (PVOID)hev); if (tid == -1) ERRMSG( "_beginthread") rc = WinWaitEventSem( hev, 4000); if (!rc) break; if (rc != ERROR_TIMEOUT) ERRMSG( "DosWaitEventSem") rc = CamDlgBox( hwnd, IDD_LVMHANG, hev); printf( "DrvMountDrives - semaphore %s posted\n", (rc ? "was" : "was not")); } while (0); if (hev) DosCloseEventSem( hev); if (pErr) printf( "DrvMountDrives - %s - rc= 0x%lx\n", pErr, rc); return; }
/** * Returns the spawn2 semaphore lazily creating it or making sure it's * available in the given process (the current process if NULL). Will return * NULLHANDLE if lazy creation fails. Must be called under global_lock(). */ unsigned long global_spawn2_sem(ProcDesc *proc) { APIRET arc; if (!proc) proc = find_proc_desc(getpid()); ASSERT(proc); if (gpData->spawn2_sem == NULLHANDLE) { ASSERT(proc->spawn2_sem == NULLHANDLE); arc = DosCreateEventSem(NULL, &gpData->spawn2_sem, DC_SEM_SHARED | DCE_AUTORESET, FALSE); if (arc != NO_ERROR) return NULLHANDLE; ASSERT(gpData->spawn2_sem_refcnt == 0); gpData->spawn2_sem_refcnt = 1; proc->spawn2_sem = gpData->spawn2_sem; } else if (proc->spawn2_sem == NULLHANDLE) { arc = DosOpenEventSem(NULL, &gpData->spawn2_sem); ASSERT_MSG(arc == NO_ERROR, "%ld %lx", arc, gpData->spawn2_sem); ASSERT(gpData->spawn2_sem_refcnt != 0); ++gpData->spawn2_sem_refcnt; proc->spawn2_sem = gpData->spawn2_sem; } TRACE("spawn2_sem %lx (refcnt %d)\n", proc->spawn2_sem, gpData->spawn2_sem_refcnt); return proc->spawn2_sem; }
int main(int argc, char *argv[]) { int do_load,do_unload,do_help,do_path; do_load=do_unload=do_help=do_path=0; char basepath[CCHMAXPATH]; if (argc == 1) do_help = 1; else { for (int i=1; i < argc; i++) { if (strnicmp(argv[i],"-l", 2) == 0) do_load = 1; else if (strnicmp(argv[i],"-u", 2) == 0) do_unload = 1; else if (strnicmp(argv[i],"-h", 2) == 0) do_help = 1; else if (strnicmp(argv[i],"-?", 2) == 0) do_help = 1; else if (strnicmp(argv[i],"-p", 2) == 0) { if (argc > i+1) { strcpy(basepath, argv[i+1]); if (basepath[strlen(basepath)] !='\\') { strcat(basepath, "\\"); } do_path = 1; } else { do_help = 1; } } } } if (do_help) { printf("%s for OS/2 preloader\n"\ "\n"\ "Usage: %s [-h] [-l | -u] [-p path]\n"\ " -h display this help\n"\ " -l load modules\n"\ " -u unload modules\n"\ " -p specify fully qualified path to directory where EXE is located\n", MOZ_APP_DISPLAYNAME, argv[0]); return(1); } if (do_unload) { HEV hev = NULLHANDLE; if (DosOpenEventSem(SEMNAME, &hev) == NO_ERROR) { if (DosPostEventSem(hev) == NO_ERROR) { if (DosCloseEventSem(hev) == NO_ERROR) { return(0); } } } printf("%s for OS/2 preloader is not running\n", MOZ_APP_DISPLAYNAME); return(1); } if (do_path == 0) { /* Get the name of this EXE and use its location as the path */ HMODULE hmodule; DosQueryModFromEIP(&hmodule, NULL, 0, NULL, NULL, (ULONG)ForceModuleLoad); DosQueryModuleName(hmodule, CCHMAXPATH, basepath); char *pchar = strrchr(basepath, '\\'); pchar++; *pchar = '\0'; } if (do_load) { ULONG ulCurMaxFH; LONG ulReqFH = 40; DosSetRelMaxFH(&ulReqFH, &ulCurMaxFH); HEV hev; if (DosCreateEventSem(SEMNAME, &hev, DC_SEM_SHARED, FALSE) != NO_ERROR) { printf("%s for OS/2 preloader is already running\n", MOZ_APP_DISPLAYNAME); return(1); } /* Add directory where EXE is located to LIBPATH */ DosSetExtLIBPATH(basepath, BEGIN_LIBPATH); /* loop through list loading named modules */ char filepath[CCHMAXPATH]; HMODULE hmod; int i = 0, nummodules = 0; while (bindir[i]) { strcpy(filepath,basepath); strcat(filepath,bindir[i]); if (DosLoadModule(NULL, 0, filepath, &hmod) == NO_ERROR) { ForceModuleLoad(hmod); nummodules++; } i++; } i = 0; while (compdir[i]) { strcpy(filepath, basepath); strcat(filepath, "COMPONENTS\\"); strcat(filepath, compdir[i]); if (DosLoadModule(NULL, 0, filepath, &hmod) == NO_ERROR) { ForceModuleLoad(hmod); nummodules++; } i++; } if (nummodules > 0) { if (DosWaitEventSem(hev, SEM_INDEFINITE_WAIT) != NO_ERROR) { printf("DosWaitEventSem failed\n"); return(1); } if (DosCloseEventSem(hev) != NO_ERROR) { printf("DosCloseEventSem failed\n"); return(1); } } else { printf("No modules available to load\n"); } } return(0); }
MRESULT EXPENTRY WndProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2 ) { // static POINTS DragStartPtrPos; POINTL ptl; static char Row, Col; static BOOL HasMoved = FALSE; static BOOL IntroSoundPlayed = FALSE; static BOOL RealPaint = TRUE; // indicates whether the board // has to be repainted or just copied INT aktscan; CHAR msgtext[256]; ULONG ulResponse; // ERRORID errId; switch( msg ){ case WM_CREATE: if( !InfoData.LoadHigh() ){ // get previously saved highscores InfoData.ResetHigh(); WinMessageBox( HWND_DESKTOP, hwndMain, "The file scores.dat " \ "(which is in the current directory) was somehow corrupted." \ " All Highscores will be reset to Zero.", "Error when loading Highscores", 0, MB_OK | MB_INFORMATION ); } // allocate memory for global variables; see GLOBALS struct in tgraph.h pg = new GLOBALS; // initialize globals to zero memset( pg, 0, sizeof( GLOBALS )); // store globals pointer into client window words; see WinRegisterClass // WinSetWindowULong( hwnd, QWL_USER, (ULONG) pg ); wcprintf("1: %x", WinGetLastError( hab ) ); DosCreateEventSem( NULL, &hevWaitAfterScan, 0, FALSE ); // Sem is created in reset state DosCreateEventSem( NULL, &hevHiScoreWin, 0, FALSE ); DosCreateEventSem( NULL, &hevWaitAfterSound, 0, FALSE ); DosCreateEventSem( NULL, &hevWaitSoundReady, 0, TRUE ); // Sem is created in posted state // hevWaitAfterScan and hewWaitAfterSound are used to indicate // when the respective WM_CREATE routines are done. // after that they are in posted state, as desired // initialize globals with important data pg->hab = hab; pg->hwndClient = hwnd; pg->hwndFrame = WinQueryWindow( hwnd, QW_PARENT ); pg->hwndTitlebar = WinWindowFromID( pg->hwndFrame, FID_TITLEBAR ); pg->hwndMenubar = WinWindowFromID( pg->hwndFrame, FID_MENU ); // create graphics and sound threads pg->tidTSound = _beginthread( &threadsound, NULL, LEN_STACK, NULL ); pg->tidTGraph = _beginthread( &threadgraph, NULL, LEN_STACK, NULL ); DosWaitEventSem( hevWaitAfterSound, SEM_INDEFINITE_WAIT ); WinPostMsg( pg->hwndTSound, WM_SOUND_INTRO, MPFROMHWND(hwnd), 0 ); // wait for the sound's WM_CREATE DosWaitEventSem( hevWaitAfterScan, SEM_INDEFINITE_WAIT ); // wait for the graphics' WM_CREATE InfoData.ShipsNotFound = GBoard.GetShipNumber(); wcprintf("create: %x", WinGetLastError( hab ) ); return (MRESULT)0; case WM_CONTROL: break; case WM_QUIT: break; case WM_CLOSE: // this message is sent before WM_QUIT InfoData.SaveHigh( WinGetCurrentTime(hab) ); // save the highscores and provide a random seed // get pointer to globals from window words // pg = (PGLOBALS) WinQueryWindowULong( hwnd, QWL_USER ); // tell object windows to quit, then exit their threads // WinSendMsg( pg->hwndTGraph, WM_DESTROY, mp1, mp2 ); WinPostMsg( pg->hwndTGraph, WM_QUIT, mp1, mp2 ); // WinSendMsg( pg->hwndTSound, WM_DESTROY, mp1, mp2 ); WinPostMsg( pg->hwndTSound, WM_QUIT, mp1, mp2 ); DosCloseEventSem( hevWaitAfterScan ); DosCloseEventSem( hevHiScoreWin ); DosCloseEventSem( hevWaitAfterSound ); DosCloseEventSem( hevWaitSoundReady ); WriteProfile( hab ); delete pg; return (MRESULT) 0; case WM_ERASEBACKGROUND: wcprintf("erasebackground"); // return (MRESULT) FALSE; return (MRESULT) TRUE; case WM_PAINT: /////////////////////////////////// { RECTL rectl; WinQueryWindowRect( pg->hwndClient, &rectl ); wcprintf("Linienrechteck: Breite: %d H”he: %d", rectl.xRight, rectl.yTop ); // test size: GpiSetColor( hpsGlob, CLR_RED ); ptl.x = rectl.xLeft; ptl.y = rectl.yBottom; GpiMove( hpsGlob, &ptl ); ptl.x = rectl.xRight; ptl.y = rectl.yTop; GpiLine( hpsGlob, &ptl ); } /////////////////////////// break; case WM_SIZE: wcprintf("main wnd function wm-size"); RealPaint = TRUE; GBoard.SetPMBoardValues( SHORT1FROMMP( mp2 ), SHORT2FROMMP( mp2 ) ); WndResize( hwnd ); wcprintf("size: %x", WinGetLastError( hab ) ); break; case WM_BEGINDRAG: WinSetCapture( HWND_DESKTOP, hwnd ); // capture the mouse pointer GBoard.SetfDrag( TRUE ); // indicate that mouse is being dragged GBoard.ResetFirstDraw(); // for initialization of drag op. fHideSquare = TRUE; WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), MPFROM2SHORT( 0, 0 ) ); // GBoard.ShowPointerPos( hwnd, 0, 0 ); // removes the square ptl.x = SHORT1FROMMP(mp1); ptl.y = SHORT2FROMMP(mp1); Row = GBoard.GetBoardRow( ptl.y ); // starting point of drag Col = GBoard.GetBoardCol( ptl.x ); // operation; static! return (MRESULT)TRUE; case WM_MOUSEMOVE: if( GBoard.GetfDrag() ){ // if mouse is being dragged WinSendMsg( pg->hwndTGraph, WM_DRAWDRAGLINE, mp1, MPFROM2SHORT( Row, Col ) ); HasMoved = TRUE; } else { // mouse is moved normally if( !fHideSquare ) WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), mp1 ); // GBoard.ShowPointerPos( hwnd, SHORT1FROMMP(mp1), // SHORT2FROMMP(mp1)); } break; case WM_ENDDRAG: WinSetCapture( HWND_DESKTOP, NULLHANDLE ); // release the captured // mouse pointer if( HasMoved ){ // mousemove has actually been moved WinSendMsg( pg->hwndTGraph, WM_MARKDRAGLINE, MPFROM2SHORT( Row, Col ), 0 ); HasMoved = FALSE; } GBoard.SetfDrag( FALSE ); GBoard.ClearDrawPoint(); // because no square is drawn right now fHideSquare = FALSE; WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), mp1 ); // GBoard.ShowPointerPos( hwnd, SHORT1FROMMP(mp1), SHORT2FROMMP(mp1)); // draws square at the current ptr pos break; case WM_CHAR: // key was pressed if( SHORT2FROMMP( mp2 ) != VK_SPACE ) break; // only space is interesting if( GBoard.GetfDrag() ) break; // do nothing while dragging if( !GBoard.GetfShowLines() ){ // lines not visible yet GBoard.SetfShowLines( TRUE ); WinSendMsg( pg->hwndTGraph, WM_DISPLAYLINES, 0, 0 ); } break; case WM_BUTTON1CLICK: if( !InfoData.ShipsNotFound ) break; // game is finished ptl.x = (LONG)SHORT1FROMMP( mp1 ); ptl.y = (LONG)SHORT2FROMMP( mp1 ); Row = GBoard.GetBoardRow( ptl.y ); Col = GBoard.GetBoardCol( ptl.x ); if( !Row || !Col ) break; fHideSquare = TRUE; WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), MPFROM2SHORT( 0, 0 ) ); // GBoard.ShowPointerPos( hwnd, 0, 0 ); // hides pointer square if(( aktscan = GBoard.GetDiscovered( Row, Col )) != -1 ){ WinSendMsg( pg->hwndTGraph, WM_DRAWPMPLACE, MPFROMHWND(hwnd), MPFROMSH2CH( MAKESHORT(Row, Col), (CHAR)aktscan,(CHAR)TRUE)); // umstricken auf WinPostMsg // toggle Place display } else { // scan Place DosResetEventSem( hevWaitAfterScan, &ulResponse ); // DosBeep(500, 150 ); WinPostMsg( pg->hwndTGraph, WM_GRAPH_SCAN, MPFROMHWND(hwnd), MPFROM2SHORT( Row, Col ) ); // DosBeep( 800, 150 ); WinWaitEventSem( hevWaitAfterScan, SEM_INDEFINITE_WAIT ); // DosBeep( 1000, 150 ); // first the scanning sounds must be played (and finished) aktscan = GBoard.Scan( Row, Col ); if( aktscan == GBoard.GetShipNumber() + 10 ){ InfoData.ShipsNotFound--; WinPostMsg( pg->hwndTSound, WM_SOUND_FOUNDSHIP, MPFROMHWND(hwnd), 0 ); } else { if( aktscan ) WinPostMsg( pg->hwndTSound, WM_SOUND_FOUND, MPFROMHWND(hwnd), MPFROMLONG( aktscan ) ); else WinPostMsg( pg->hwndTSound, WM_SOUND_FOUND0, MPFROMHWND(hwnd), 0 ); } WinWaitEventSem( hevWaitAfterScan, SEM_INDEFINITE_WAIT ); // waits until scanning is done, and only then displays the // field icon // hps = WinGetPS( hwnd ); WinSendMsg( pg->hwndTGraph, WM_DRAWPMPLACE, MPFROMHWND(hwnd), MPFROMSH2CH( MAKESHORT(Row, Col), (CHAR)aktscan,(CHAR)TRUE)); // umstricken auf WinPostMsg WinPostMsg( pg->hwndTGraph, WM_SHOWSTATUSLINE, 0, 0 ); // ShowStatusLine( hps, GBoard.MovesNeeded(), InfoData.ShipsNotFound, // GBoard.GetWinWidth(), GBoard.GetWinHeight() ); // WinReleasePS( hps ); if( !InfoData.ShipsNotFound ){ // game is finished, all ships found Score = GBoard.MovesNeeded(); if ( !InfoData.ReturnLastHigh() // still space in the hiscore table || Score < InfoData.ReturnLastHigh() ){ // player kicks last one out // player enters highscore table WinPostMsg( pg->hwndTSound, WM_SOUND_NEWHISCORE, MPFROMHWND(hwnd), 0 ); WinWaitEventSem( hevHiScoreWin, SEM_INDEFINITE_WAIT ); // waits until the NEWHISCORE sound is actually played WinDlgBox( HWND_DESKTOP, hwnd, HighScoreDlgProc, (HMODULE)0, IDR_HIGHSCOREDLG, NULL ); WinPostMsg( hwnd, WM_COMMAND, MPFROMSHORT(IDM_GAMEHIGH), (MPARAM)0 ); // show highscore-table DosResetEventSem( hevHiScoreWin, &ulResponse ); // resets the sem again } else { WinPostMsg( pg->hwndTSound, WM_SOUND_LOST, MPFROMHWND(hwnd), 0 ); WinWaitEventSem( hevHiScoreWin, SEM_INDEFINITE_WAIT ); // waits until the NEWHISCORE sound is actually played sprintf( msgtext, "You needed %d moves to find the lost ships. " \ "To enter the highscore list you need %d moves." \ " So try again!", Score, InfoData.ReturnLastHigh() - 1 ); WinMessageBox( HWND_DESKTOP, hwnd, msgtext, "Oh, Shit!", 0, MB_OK | MB_INFORMATION | MB_HELP ); } } } fHideSquare = FALSE; WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), MPFROM2SHORT( ptl.x, ptl.y ) ); // GBoard.ShowPointerPos( hwnd, ptl.x, ptl.y ); // redisplay ptr square break; case WM_BUTTON2CLICK: fHideSquare = TRUE; WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), MPFROM2SHORT( 0, 0 ) ); ptl.x = (LONG)SHORT1FROMMP( mp1 ); ptl.y = (LONG)SHORT2FROMMP( mp1 ); Row = GBoard.GetBoardRow( ptl.y ); Col = GBoard.GetBoardCol( ptl.x ); WinSendMsg( pg->hwndTGraph, WM_DRAWPMMARK, MPFROMHWND(hwnd), MPFROM2SHORT( Row, Col ) ); fHideSquare = FALSE; WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), MPFROM2SHORT( ptl.x, ptl.y ) ); break; case WM_COMMAND: switch( SHORT1FROMMP( mp1 ) ){ case IDM_GAMENEW: GBoard.NewGame(); InfoData.ShipsNotFound = GBoard.GetShipNumber(); RealPaint = TRUE; WinInvalidateRect( hwnd, NULL, TRUE ); break; case IDM_GAMESETTINGS: if( WinDlgBox( HWND_DESKTOP, hwndFrame, GameSettingsDlgProc, (HMODULE)0, IDR_GAMESETTINGSDLG, NULL ) ){ // screen must be repainted RealPaint = TRUE; WinInvalidateRect( hwnd, NULL, TRUE ); } break; case IDM_GAMEHIGH: if( !WinDlgBox( HWND_DESKTOP, hwndFrame, ShowHighDlgProc, (HMODULE)0, IDR_SHOWHIGHDLG, NULL ) ){ // user requested "Clear" if( WinMessageBox( HWND_DESKTOP, hwndMain, "Do you really want to eradicate all those " \ "arduously achieved highscores?", "Clear Highscores", 0, MB_OKCANCEL | MB_WARNING ) == MBID_OK ) InfoData.ResetHigh(); } break; case IDM_HELPINDEX: // help index WinSendMsg( hwndHelp, HM_HELP_INDEX, 0, 0 ); break; case IDM_HELPGENERAL: // general help WinSendMsg( hwndHelp, HM_EXT_HELP, 0, 0 ); break; case IDM_HELPEXTENDED: // help on help (system page) WinSendMsg( hwndHelp, HM_DISPLAY_HELP, 0, 0 ); break; case IDM_HELPKEYS: // keys help WinSendMsg( hwndHelp, HM_KEYS_HELP, 0, 0 ); break; case IDM_HELPPRODUCTINFO: ulResponse = WinDlgBox( HWND_DESKTOP, hwndFrame, ProdInfoDlgProc, (HMODULE)0, IDR_PRODINFODLG, NULL ); break; } break; case HM_QUERY_KEYS_HELP: // system asks which page to display return MRFROMSHORT( PANEL_HELPKEYS ); case HM_HELPSUBITEM_NOT_FOUND: return (MRESULT)FALSE; case WM_USER_ACK: // graphics task finished its work // DosBeep( 1000, 150 ); switch( (ULONG)mp1 ){ case WM_USER_PAINT: WinQueryPointerPos( HWND_DESKTOP, &ptl ); WinMapWindowPoints( HWND_DESKTOP, hwnd, &ptl, 1); fHideSquare = FALSE; WinSendMsg( pg->hwndTGraph, WM_SHOWPOINTERPOS, MPFROMHWND(hwnd), MPFROM2SHORT( ptl.x, ptl.y ) ); // GBoard.ShowPointerPos( hwnd, ptl.x, ptl.y ); // painting has finished, square can be displayed now break; } break; case WM_SOUND_ACK: switch( (ULONG)mp1 ){ case WM_SOUND_INTRO: break; } break; default: return (MRESULT)WinDefWindowProc( hwnd, msg, mp1, mp2 ); } // end switch( msg ) return (MRESULT)WinDefWindowProc( hwnd, msg, mp1, mp2 ); } // end MRESULT EXPENTRY WndProc()
void ap_mpm_child_main(apr_pool_t *pconf) { ap_listen_rec *lr = NULL; int requests_this_child = 0; int rv = 0; unsigned long ulTimes; int my_pid = getpid(); ULONG rc, c; HQUEUE workq; apr_pollset_t *pollset; int num_listeners; TID server_maint_tid; void *sb_mem; /* Stop Ctrl-C/Ctrl-Break signals going to child processes */ DosSetSignalExceptionFocus(0, &ulTimes); set_signals(); /* Create pool for child */ apr_pool_create(&pchild, pconf); ap_run_child_init(pchild, ap_server_conf); /* Create an event semaphore used to trigger other threads to shutdown */ rc = DosCreateEventSem(NULL, &shutdown_event, 0, FALSE); if (rc) { ap_log_error(APLOG_MARK, APLOG_ERR, APR_FROM_OS_ERROR(rc), ap_server_conf, "unable to create shutdown semaphore, exiting"); clean_child_exit(APEXIT_CHILDFATAL); } /* Gain access to the scoreboard. */ rc = DosGetNamedSharedMem(&sb_mem, ap_scoreboard_fname, PAG_READ|PAG_WRITE); if (rc) { ap_log_error(APLOG_MARK, APLOG_ERR, APR_FROM_OS_ERROR(rc), ap_server_conf, "scoreboard not readable in child, exiting"); clean_child_exit(APEXIT_CHILDFATAL); } ap_calc_scoreboard_size(); ap_init_scoreboard(sb_mem); /* Gain access to the accpet mutex */ rc = DosOpenMutexSem(NULL, &ap_mpm_accept_mutex); if (rc) { ap_log_error(APLOG_MARK, APLOG_ERR, APR_FROM_OS_ERROR(rc), ap_server_conf, "accept mutex couldn't be accessed in child, exiting"); clean_child_exit(APEXIT_CHILDFATAL); } /* Find our pid in the scoreboard so we know what slot our parent allocated us */ for (child_slot = 0; ap_scoreboard_image->parent[child_slot].pid != my_pid && child_slot < HARD_SERVER_LIMIT; child_slot++); if (child_slot == HARD_SERVER_LIMIT) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "child pid not found in scoreboard, exiting"); clean_child_exit(APEXIT_CHILDFATAL); } ap_my_generation = ap_scoreboard_image->parent[child_slot].generation; memset(ap_scoreboard_image->servers[child_slot], 0, sizeof(worker_score) * HARD_THREAD_LIMIT); /* Set up an OS/2 queue for passing connections & termination requests * to worker threads */ rc = DosCreateQueue(&workq, QUE_FIFO, apr_psprintf(pchild, "/queues/httpd/work.%d", my_pid)); if (rc) { ap_log_error(APLOG_MARK, APLOG_ERR, APR_FROM_OS_ERROR(rc), ap_server_conf, "unable to create work queue, exiting"); clean_child_exit(APEXIT_CHILDFATAL); } /* Create initial pool of worker threads */ for (c = 0; c < ap_min_spare_threads; c++) { // ap_scoreboard_image->servers[child_slot][c].tid = _beginthread(worker_main, NULL, 128*1024, (void *)c); } /* Start maintenance thread */ server_maint_tid = _beginthread(server_maintenance, NULL, 32768, NULL); /* Set up poll */ for (num_listeners = 0, lr = ap_listeners; lr; lr = lr->next) { num_listeners++; } apr_pollset_create(&pollset, num_listeners, pchild, 0); for (lr = ap_listeners; lr != NULL; lr = lr->next) { apr_pollfd_t pfd = { 0 }; pfd.desc_type = APR_POLL_SOCKET; pfd.desc.s = lr->sd; pfd.reqevents = APR_POLLIN; pfd.client_data = lr; apr_pollset_add(pollset, &pfd); } /* Main connection accept loop */ do { apr_pool_t *pconn; worker_args_t *worker_args; int last_poll_idx = 0; apr_pool_create(&pconn, pchild); worker_args = apr_palloc(pconn, sizeof(worker_args_t)); worker_args->pconn = pconn; if (num_listeners == 1) { rv = apr_socket_accept(&worker_args->conn_sd, ap_listeners->sd, pconn); } else { const apr_pollfd_t *poll_results; apr_int32_t num_poll_results; rc = DosRequestMutexSem(ap_mpm_accept_mutex, SEM_INDEFINITE_WAIT); if (shutdown_pending) { DosReleaseMutexSem(ap_mpm_accept_mutex); break; } rv = APR_FROM_OS_ERROR(rc); if (rv == APR_SUCCESS) { rv = apr_pollset_poll(pollset, -1, &num_poll_results, &poll_results); DosReleaseMutexSem(ap_mpm_accept_mutex); } if (rv == APR_SUCCESS) { if (last_poll_idx >= num_listeners) { last_poll_idx = 0; } lr = poll_results[last_poll_idx++].client_data; rv = apr_socket_accept(&worker_args->conn_sd, lr->sd, pconn); last_poll_idx++; } } if (rv != APR_SUCCESS) { if (!APR_STATUS_IS_EINTR(rv)) { ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, "apr_socket_accept"); clean_child_exit(APEXIT_CHILDFATAL); } } else { DosWriteQueue(workq, WORKTYPE_CONN, sizeof(worker_args_t), worker_args, 0); requests_this_child++; } if (ap_max_requests_per_child != 0 && requests_this_child >= ap_max_requests_per_child) break; } while (!shutdown_pending && ap_my_generation == ap_scoreboard_image->global->running_generation); ap_scoreboard_image->parent[child_slot].quiescing = 1; DosPostEventSem(shutdown_event); DosWaitThread(&server_maint_tid, DCWW_WAIT); if (is_graceful) { char someleft; /* tell our worker threads to exit */ for (c=0; c<HARD_THREAD_LIMIT; c++) { if (ap_scoreboard_image->servers[child_slot][c].status != SERVER_DEAD) { DosWriteQueue(workq, WORKTYPE_EXIT, 0, NULL, 0); } } do { someleft = 0; for (c=0; c<HARD_THREAD_LIMIT; c++) { if (ap_scoreboard_image->servers[child_slot][c].status != SERVER_DEAD) { someleft = 1; DosSleep(1000); break; } } } while (someleft); } else { DosPurgeQueue(workq); for (c=0; c<HARD_THREAD_LIMIT; c++) { if (ap_scoreboard_image->servers[child_slot][c].status != SERVER_DEAD) { DosKillThread(ap_scoreboard_image->servers[child_slot][c].tid); } } } apr_pool_destroy(pchild); }
int main(VOID) { HMUX hmuxHandAny = NULLHANDLE; /* Muxwaithandle */ HEV hev[2] = {0}; /* Event semaphores */ SEMRECORD apsr[2] = {{0}}; /* Semaphore records */ SEMRECORD semrecQuery[2] = {{0}}; /* Pointer from query */ ULONG cQueryRec = 2; /* Number of records found by query */ ULONG fQueryFlags = 0; /* Attribute flags returned by query */ APIRET rc = NO_ERROR; /* Return code */ ULONG ulLoop = 0; /* Loop count */ ULONG ulSem = 0; for (ulLoop = 0; ulLoop < 2; ulLoop++) { rc = DosCreateEventSem((PSZ) NULL, &hev[ulLoop], 0, FALSE); if (rc != NO_ERROR) { printf("DosCreateEventSem error: return code = %u\n", rc); return 1; } apsr[ulLoop].hsemCur = (HSEM) hev[ulLoop], apsr[ulLoop].ulUser = 0; } /* endfor */ rc = DosCreateMuxWaitSem((PSZ) NULL, &hmuxHandAny, 2L, apsr, DCMW_WAIT_ANY); if (rc != NO_ERROR) { printf("DosCreateMuxWaitSem error: return code = %u\n", rc); return 1; } /* Query information about the MuxWait semaphore */ rc = DosQueryMuxWaitSem(hmuxHandAny, /* Semaphore handle */ &cQueryRec, /* Number of records */ (PSEMRECORD) semrecQuery, /* Pointer to Semrecords */ &fQueryFlags); /* Flags returned */ if (rc != NO_ERROR) { printf("DosQueryMuxWaitSem error: return code = %u\n", rc); return 1; } else { printf("DosQueryMuxWaitSem found %u semaphore records\n", cQueryRec); } /* endif */ return NO_ERROR; }
/* Creates the the worker threads. */ static void incdep_init (struct floc *f) { unsigned i; #if defined (HAVE_PTHREAD) && !defined (CONFIG_WITHOUT_THREADS) int rc; pthread_attr_t attr; #elif defined (WINDOWS32) unsigned tid; uintptr_t hThread; #elif defined (__OS2__) int rc; int tid; #endif (void)f; /* heap hacks */ #ifdef __APPLE__ incdep_zone = malloc_create_zone (0, 0); if (!incdep_zone) incdep_zone = malloc_default_zone (); #endif /* create the mutex and two condition variables / event objects. */ #if defined (HAVE_PTHREAD) && !defined (CONFIG_WITHOUT_THREADS) rc = pthread_mutex_init (&incdep_mtx, NULL); if (rc) fatal (f, _("pthread_mutex_init failed: err=%d"), rc); rc = pthread_cond_init (&incdep_cond_todo, NULL); if (rc) fatal (f, _("pthread_cond_init failed: err=%d"), rc); rc = pthread_cond_init (&incdep_cond_done, NULL); if (rc) fatal (f, _("pthread_cond_init failed: err=%d"), rc); #elif defined (WINDOWS32) InitializeCriticalSection (&incdep_mtx); incdep_hev_todo = CreateEvent (NULL, TRUE /*bManualReset*/, FALSE /*bInitialState*/, NULL); if (!incdep_hev_todo) fatal (f, _("CreateEvent failed: err=%d"), GetLastError()); incdep_hev_done = CreateEvent (NULL, TRUE /*bManualReset*/, FALSE /*bInitialState*/, NULL); if (!incdep_hev_done) fatal (f, _("CreateEvent failed: err=%d"), GetLastError()); incdep_hev_todo_waiters = 0; incdep_hev_done_waiters = 0; #elif defined (__OS2__) _fmutex_create (&incdep_mtx, 0); rc = DosCreateEventSem (NULL, &incdep_hev_todo, 0, FALSE); if (rc) fatal (f, _("DosCreateEventSem failed: rc=%d"), rc); rc = DosCreateEventSem (NULL, &incdep_hev_done, 0, FALSE); if (rc) fatal (f, _("DosCreateEventSem failed: rc=%d"), rc); incdep_hev_todo_waiters = 0; incdep_hev_done_waiters = 0; #endif /* create the worker threads and associated per thread data. */ incdep_terminate = 0; if (incdep_are_threads_enabled()) { incdep_num_threads = sizeof (incdep_threads) / sizeof (incdep_threads[0]); if (incdep_num_threads + 1 > job_slots) incdep_num_threads = job_slots <= 1 ? 1 : job_slots - 1; for (i = 0; i < incdep_num_threads; i++) { /* init caches */ unsigned rec_size = sizeof (struct incdep_variable_in_set); if (rec_size < sizeof (struct incdep_variable_def)) rec_size = sizeof (struct incdep_variable_def); if (rec_size < sizeof (struct incdep_recorded_file)) rec_size = sizeof (struct incdep_recorded_file); alloccache_init (&incdep_rec_caches[i], rec_size, "incdep rec", incdep_cache_allocator, (void *)(size_t)i); alloccache_init (&incdep_dep_caches[i], sizeof(struct dep), "incdep dep", incdep_cache_allocator, (void *)(size_t)i); strcache2_init (&incdep_dep_strcaches[i], "incdep dep", /* name */ 65536, /* hash size */ 0, /* default segment size*/ #ifdef HAVE_CASE_INSENSITIVE_FS 1, /* case insensitive */ #else 0, /* case insensitive */ #endif 0); /* thread safe */ strcache2_init (&incdep_var_strcaches[i], "incdep var", /* name */ 32768, /* hash size */ 0, /* default segment size*/ 0, /* case insensitive */ 0); /* thread safe */ /* create the thread. */ #if defined (HAVE_PTHREAD) && !defined (CONFIG_WITHOUT_THREADS) rc = pthread_attr_init (&attr); if (rc) fatal (f, _("pthread_attr_init failed: err=%d"), rc); /*rc = pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE); */ rc = pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); if (rc) fatal (f, _("pthread_attr_setdetachstate failed: err=%d"), rc); rc = pthread_create(&incdep_threads[i], &attr, incdep_worker_pthread, (void *)(size_t)i); if (rc) fatal (f, _("pthread_mutex_init failed: err=%d"), rc); pthread_attr_destroy (&attr); #elif defined (WINDOWS32) tid = 0; hThread = _beginthreadex (NULL, 128*1024, incdep_worker_windows, (void *)i, 0, &tid); if (hThread == 0 || hThread == ~(uintptr_t)0) fatal (f, _("_beginthreadex failed: err=%d"), errno); incdep_threads[i] = (HANDLE)hThread; #elif defined (__OS2__) tid = _beginthread (incdep_worker_os2, NULL, 128*1024, (void *)i); if (tid <= 0) fatal (f, _("_beginthread failed: err=%d"), errno); incdep_threads[i] = tid; #endif } } else incdep_num_threads = 0; incdep_initialized = 1; }
BOOL Initialize(int argc, char* argv[]) { ULONG flCreate; PID pid; TID tid; debOut = fopen ("\\PIPE\\WATCHCAT", "w"); if (debOut) { fprintf(debOut, "MakMan/2 Init\n"); fflush(debOut); } GetScoresFromIni(); /* * create all semaphores for mutual exclusion and event timing */ if ( DosCreateEventSem( NULL, &hevTick , DC_SEM_SHARED, FALSE) || DosCreateEventSem( NULL, &hevSound , DC_SEM_SHARED, FALSE) || DosCreateEventSem( NULL, &hevTermGame , DC_SEM_SHARED, FALSE) || DosCreateEventSem( NULL, &hevTermSound, DC_SEM_SHARED, FALSE) ) return (FALSE); /* failed to create a semaphore */ WinShowPointer( HWND_DESKTOP, TRUE); habMain = WinInitialize( 0); if( !habMain) return( FALSE); hmqMain = WinCreateMsgQueue( habMain,0); if( !hmqMain) return( FALSE); WinLoadString( habMain, 0, IDS_TITLEBAR, sizeof(szTitle), szTitle); WinLoadString( habMain, 0, IDS_ERRORTITLE, sizeof(szErrorTitle), szErrorTitle); if( !WinRegisterClass( habMain , (PCH)szTitle , ClientWndProc , CS_SIZEREDRAW | CS_MOVENOTIFY , 0 )) return( FALSE); flCreate = (FCF_TITLEBAR | FCF_SYSMENU | FCF_MENU | FCF_BORDER | FCF_ICON | FCF_AUTOICON | FCF_ACCELTABLE | FCF_MINBUTTON | FCF_SHELLPOSITION ); hwndFrame = WinCreateStdWindow( HWND_DESKTOP, /* handle of the parent window */ 0, /* frame-window style */ &flCreate, /* creation flags */ szTitle, /* client-window class name */ szTitle, /* address of title-bar text */ WS_SYNCPAINT, /* client-window style */ 0, /* handle of the resource module */ IDR_MAIN, /* frame-window identifier */ &hwndClient); /* address of client-window handle */ if( !hwndFrame) return( FALSE); if (debOut) { fprintf(debOut, "Creating engine\n"); fflush(debOut); } // // Instantiate the Gfx Output engine // if (argc == 2) { strlwr(argv[1]); // make lower case if (strcmp(argv[1], "gpi") == 0) GfxEng = new gpi; else if (strcmp(argv[1], "dive") == 0) GfxEng = new dive; else { char buf[200]; sprintf(buf, "Usage : MakMan [gpi | dive]\n" "Unknown option %s\n", argv[1]); WinMessageBox(HWND_DESKTOP, hwndFrame, (PSZ) buf, (PSZ) szTitle, 0, MB_MOVEABLE | MB_CUACRITICAL | MB_CANCEL ); return FALSE; } } else GfxEng = new gpi; SndEng = new mmpm2; if (debOut) { fprintf(debOut, "Gfx engine : %p Snd : %p\n", GfxEng, SndEng); fflush(debOut); } if (!GfxEng->open()) { WinMessageBox(HWND_DESKTOP, hwndFrame, (PSZ) "Can't initialize selected Graphics Engine", (PSZ) szTitle, 0, MB_MOVEABLE | MB_CUACRITICAL | MB_CANCEL ); return FALSE; } if (!SndEng->open()) { WinMessageBox(HWND_DESKTOP, hwndFrame, (PSZ) "Can't initialize MMPM2 Sound Engine\nSound won't be available for this session", (PSZ) szTitle, 0, MB_MOVEABLE | MB_CUACRITICAL | MB_CANCEL ); } // // Finish up initializing the Window // // restore the previous position on screen int retc = WinRestoreWindowPos(szAppName, szKeyPosition, hwndFrame); if (debOut) { fprintf(debOut, "Restored old pos : %i\n",retc); fflush(debOut); } cxWidthBorder = (LONG) WinQuerySysValue(HWND_DESKTOP, SV_CXBORDER); cyWidthBorder = (LONG) WinQuerySysValue(HWND_DESKTOP, SV_CYBORDER); cyTitleBar = (LONG) WinQuerySysValue(HWND_DESKTOP, SV_CYTITLEBAR); cyMenu = (LONG) WinQuerySysValue(HWND_DESKTOP, SV_CYMENU); cyScreen = (LONG) WinQuerySysValue(HWND_DESKTOP, SV_CYSCREEN); sizlMaxClient.cx = fieldSizeX * tileWidth + cxWidthBorder * 2; sizlMaxClient.cy = fieldSizeY * tileHeight + cyWidthBorder * 2 + cyTitleBar + cyMenu ; // And now set the window to the correct size WinSetWindowPos( hwndFrame, HWND_TOP, 0, 0, sizlMaxClient.cx, sizlMaxClient.cy, SWP_SIZE | SWP_SHOW | SWP_ACTIVATE); lByteAlignX = WinQuerySysValue( HWND_DESKTOP, SV_CXBYTEALIGN); lByteAlignY = WinQuerySysValue( HWND_DESKTOP, SV_CYBYTEALIGN); // Turn on visible region notification. WinSetVisibleRegionNotify ( hwndClient, TRUE ); // And invalidate the visible region WinPostMsg ( hwndFrame, WM_VRNENABLED, 0L, 0L ); // Enter the program in the WPS/PM task list WinQueryWindowProcess( hwndFrame, &pid, &tid); swctl.hwnd = hwndFrame; swctl.idProcess = pid; strcpy( swctl.szSwtitle, szTitle); hsw = WinAddSwitchEntry(&swctl); hwndMenu = WinWindowFromID( hwndFrame, FID_MENU); // // Disable unused menu entries // EnableMenu(IDM_LEVEL, FALSE); EnableMenu(IDM_HELPINDEX, FALSE); EnableMenu(IDM_HELPEXTENDED, FALSE); EnableMenu(IDM_HELPHELPFORHELP, FALSE); // // Look for a Joystick (driver) // APIRET rc; ULONG action; GAME_PARM_STRUCT gameParms; ULONG dataLen; rc = DosOpen(GAMEPDDNAME, &hGame, &action, 0, FILE_READONLY, FILE_OPEN, OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE, NULL); if (rc != 0) hGame = 0; else { // There is a driver loaded - can we talk to him? dataLen = sizeof(gameParms); // Look for any (Joy)sticks rc = DosDevIOCtl(hGame, IOCTL_CAT_USER, GAME_GET_PARMS, NULL, 0, NULL, &gameParms, dataLen, &dataLen); if (rc != 0 && debOut) { fprintf(debOut, "Couldn't call IOCtl for GAME$\n"); fflush(debOut); } } // ok so far? if (hGame == 0 || rc != 0) { if (debOut) { fprintf(debOut, "Joystick driver not found\n"); fflush(debOut); } DosClose(hGame); EnableMenu(IDM_JOY_A, FALSE); EnableMenu(IDM_JOY_B, FALSE); EnableMenu(IDM_CALIBRATE, FALSE); hGame = 0; } else { // all ok, deregister any superfluous menu entries // and calibrate sticks if (debOut) { fprintf(debOut, "JoyStat A: %i, B:%i\n", gameParms.useA, gameParms.useB); fflush(debOut); } /* * Keep only bits defined X and Y axis, they are bit 1 and bit 2 */ USHORT usTmp1 = gameParms.useA & GAME_USE_BOTH_NEWMASK; USHORT usTmp2 = gameParms.useB & GAME_USE_BOTH_NEWMASK; // No Joysticks if (gameParms.useA == 0 && gameParms.useB == 0) { EnableMenu(IDM_JOY_A, FALSE); EnableMenu(IDM_CAL_A, FALSE); EnableMenu(IDM_JOY_B, FALSE); EnableMenu(IDM_CAL_B, FALSE); } // One Joystick found // if usTmp2 is not 0, then Joystick 1 is an extended // type joystick (with 3 axes) but we don't care if (usTmp1 == GAME_USE_BOTH_NEWMASK && usTmp2 != GAME_USE_BOTH_NEWMASK ) { EnableMenu(IDM_JOY_B, FALSE); EnableMenu(IDM_CAL_B, FALSE); } // And now read the calibration values GAME_CALIB_STRUCT gameCalib; dataLen = sizeof(gameCalib); rc = DosDevIOCtl(hGame, IOCTL_CAT_USER, GAME_GET_CALIB, NULL, 0, NULL, &gameCalib, dataLen, &dataLen ); joyCal[1].x = gameCalib.Ax.centre; joyCal[1].y = gameCalib.Ay.centre; joyCal[2].x = gameCalib.Bx.centre; joyCal[2].y = gameCalib.By.centre; } /* * initialise help mechanism */ HelpInit(); // Set the default values for the various options... GetOptionsFromIni(); // initiate random number generator srand(time(NULL)); return TRUE; } /* end Initialize() */
static void * tf (void *arg) { if (pthread_mutex_lock (&lock)) { puts ("1st locking of lock failed"); exit (1); } struct flock fl = { .l_type = F_WRLCK, .l_start = 0, .l_whence = SEEK_SET, .l_len = 10 }; if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) { puts ("fourth fcntl failed"); exit (1); } pthread_mutex_unlock (&lock); pthread_mutex_lock (&lock2); return NULL; } static int do_test (void) { fd = create_temp_file("tst-flock2-", NULL); if (fd == -1) { puts ("create_temp_file failed"); return 1; } int i; for (i = 0; i < 20; ++i) write (fd, "foobar xyzzy", 12); pthread_barrier_t *b; #ifdef __EMX__ APIRET arc; arc = DosAllocSharedMem ((PPVOID) &b, NULL, sizeof (pthread_barrier_t), PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_GETTABLE); if (arc) { puts ("DosAllocSharedMem failed"); return 1; } b->hmtx = NULLHANDLE; arc = DosCreateMutexSem (NULL, &b->hmtx, DC_SEM_SHARED, FALSE); if (arc) { puts ("DosCreateMutexSem failed"); return 1; } b->hev = NULLHANDLE; arc = DosCreateEventSem (NULL, &b->hev, DC_SEM_SHARED | DCE_AUTORESET, FALSE); if (arc) { puts ("DosCreateEventSem failed"); return 1; } b->cnt = 0; b->cnt_max = 2; #else b = mmap (NULL, sizeof (pthread_barrier_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (b == MAP_FAILED) { puts ("mmap failed"); return 1; } pthread_barrierattr_t ba; if (pthread_barrierattr_init (&ba) != 0) { puts ("barrierattr_init failed"); return 1; } if (pthread_barrierattr_setpshared (&ba, PTHREAD_PROCESS_SHARED) != 0) { puts ("barrierattr_setpshared failed"); return 1; } if (pthread_barrier_init (b, &ba, 2) != 0) { puts ("barrier_init failed"); return 1; } if (pthread_barrierattr_destroy (&ba) != 0) { puts ("barrierattr_destroy failed"); return 1; } #endif struct flock fl = { .l_type = F_WRLCK, .l_start = 0, .l_whence = SEEK_SET, .l_len = 10 }; if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) { puts ("first fcntl failed"); return 1; } pid_t pid = fork (); if (pid == -1) { puts ("fork failed"); return 1; } if (pid == 0) { #ifdef __EMX__ arc = DosGetSharedMem (b, PAG_READ | PAG_WRITE); if (arc) { puts ("DosGetSharedMem failed"); return 1; } arc = DosOpenMutexSem (NULL, &b->hmtx); if (arc) { puts ("DosOpenMutexSem failed"); return 1; } arc = DosOpenEventSem (NULL, &b->hev); if (arc) { puts ("DosOpenEventSem failed"); return 1; } #endif /* Make sure the child does not stay around indefinitely. */ alarm (10); /* Try to get the lock. */ if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0) { puts ("child: second flock succeeded"); return 1; } } pthread_barrier_wait (b); if (pid != 0) { fl.l_type = F_UNLCK; if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) { puts ("third fcntl failed"); return 1; } } pthread_barrier_wait (b); pthread_t th; if (pid == 0) { if (pthread_mutex_lock (&lock2) != 0) { puts ("1st locking of lock2 failed"); return 1; } if (pthread_create (&th, NULL, tf, NULL) != 0) { puts ("pthread_create failed"); return 1; } /* Let the new thread run. */ sleep (1); if (pthread_mutex_lock (&lock) != 0) { puts ("2nd locking of lock failed"); return 1; } puts ("child locked file"); } pthread_barrier_wait (b); if (pid != 0) { fl.l_type = F_WRLCK; if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0) { puts ("fifth fcntl succeeded"); return 1; } puts ("file locked by child"); } pthread_barrier_wait (b); if (pid == 0) { if (pthread_mutex_unlock (&lock2) != 0) { puts ("unlock of lock2 failed"); return 1; } if (pthread_join (th, NULL) != 0) { puts ("join failed"); return 1; } puts ("child's thread terminated"); } pthread_barrier_wait (b); if (pid != 0) { fl.l_type = F_WRLCK; if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0) { puts ("fifth fcntl succeeded"); return 1; } puts ("file still locked"); } pthread_barrier_wait (b); if (pid == 0) { _exit (0); } int status; if (TEMP_FAILURE_RETRY (waitpid (pid, &status, 0)) != pid) { puts ("waitpid failed"); return 1; } puts ("child terminated"); if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0) { puts ("sixth fcntl failed"); return 1; } return status; }
int cc_execute( ckjptr(sj_buf), ck_sigfunc dofunc, ck_sigfunc failfunc ) { int rc = 0 ; TID tidThread ; ULONG semid ; ULONG ccindex ; #ifdef NT HANDLE hevThread ; #else /* NT */ HEV hevThread ; #endif /* NT */ struct _threadinfo * threadinfo = (struct _threadinfo *) TlsGetValue(TlsIndex) ; debug(F100,"cc_execute enter","",0); /* create an event semaphore for new thread */ #ifdef NT hevThread = CreateEvent( NULL, TRUE, FALSE, NULL ) ; #else DosCreateEventSem( NULL, &hevThread, DC_SEM_SHARED, FALSE ) ; #endif /* NT */ CreateCtrlCSem( FALSE, &ccindex ) ; CreateCtrlCMuxWait( ccindex, hevThread ) ; /* Begin new thread with dofunc */ tidThread = ckThreadBegin(dofunc,THRDSTKSIZ,(void *)&hevThread,TRUE, threadinfo ? threadinfo->id : NULL ); /* Wait for the event semaphore or Ctrl-C */ /* semaphore to be set */ /* when Ctrl-C semaphore is set execute failfunc */ /* and return -1 */ /* else if event semaphore is set return 0 */ semid = WaitCtrlCMuxWait( ccindex, SEM_INDEFINITE_WAIT ) ; if ( semid == 1 ) { /* Ctrl-C */ debug(F100,"cc_execute ctrl-c","",0); ResetCtrlCSem(ccindex) ; if ( !network ) { debug(F100,"cc_execute about to PurgeComm","",0); if (PurgeComm( (HANDLE) ttyfd, PURGE_TXABORT | PURGE_RXABORT )) { debug( F100, "cc_execute PurgeComm successful","",0); } else { debug( F101, "cc_execute PurgeComm failed","",GetLastError() ); } msleep(500); } ckThreadKill( tidThread ) ; rc = -1 ; (*failfunc)(0) ; } else if ( semid == 2 ) { /* Thread completed successfully */ debug(F100,"cc_execute thread completed","",0); ResetSem( hevThread ) ; } CloseCtrlCMuxWait(ccindex) ; CloseCtrlCSem( ccindex ) ; #ifdef NT CloseHandle( hevThread ) ; #ifdef NTSIG ck_ih(); #endif /* NTSIG */ #else /* NT */ DosCloseEventSem( hevThread ); #endif /* NT */ return rc ; }
int alrm_execute(ckjptr(sj_buf), int timo, ck_sighand handler, ck_sigfunc dofunc, ck_sigfunc failfunc ) /* alrm_execute */ { int rc = 0; TID tidThread ; ULONG semid ; ULONG alrmindex ; #ifdef NT HANDLE hevThread ; #else /* NT */ HEV hevThread ; #endif /* NT */ int savalrm = 0; _PROTOTYP( SIGTYP (*savhandler), (int) ); struct _threadinfo * threadinfo = (struct _threadinfo *) TlsGetValue(TlsIndex) ; debug(F100,"alrm_execute enter","",0); savalrm = alarm(timo); savhandler = signal( SIGALRM, handler ); /* create an event semaphore for new thread */ #ifdef NT hevThread = CreateEvent( NULL, TRUE, FALSE, NULL ) ; #else DosCreateEventSem( NULL, &hevThread, DC_SEM_SHARED, FALSE ) ; #endif /* NT */ CreateAlarmSigSem( FALSE, &alrmindex ) ; CreateAlarmSigMuxWait( alrmindex, hevThread ) ; /* begin new thread with dofunc */ tidThread = ckThreadBegin(dofunc,THRDSTKSIZ,(void *)&hevThread,TRUE, threadinfo ? threadinfo->id : NULL ); /* wait for the event semaphore or Ctrl-C */ /* semaphore to be set */ /* when Ctrl-C semaphore is set execute failfunc */ /* and return -1 */ /* else if event semaphore is set return 0 */ semid = WaitAlarmSigMuxWait( alrmindex, SEM_INDEFINITE_WAIT ) ; if ( semid == 1 ) { /* Alarm */ debug(F100,"alrm_execute timeout","",0); (*handler)(SIGALRM) ; ResetAlarmSigSem(alrmindex) ; if ( !network ) { debug(F100,"alrm_execute about to PurgeComm","",0); if (PurgeComm( (HANDLE) ttyfd, PURGE_TXABORT | PURGE_RXABORT )) { debug( F100, "alrm_execute PurgeComm successful","",0); } else { debug(F101,"alrm_execute PurgeComm failed","",GetLastError() ); } msleep(500); } ckThreadKill( tidThread ) ; rc = -1 ; (*failfunc)(0) ; } else if ( semid == 2 ) { /* Thread completed successfully */ debug(F100,"alrm_execute thread completed","",0); ResetSem( hevThread ) ; } CloseAlarmSigMuxWait(alrmindex) ; CloseAlarmSigSem( alrmindex ) ; #ifdef NT CloseHandle( hevThread ) ; #else /* NT */ DosCloseEventSem( hevThread ); #endif /* NT */ alarm(savalrm) ; if ( savhandler ) signal( SIGALRM, savhandler ) ; #ifdef NTSIG ck_ih(); #endif /* NTSIG */ return rc ; }
ThreadMutex_OS2() { DosCreateMutexSem(NULL, &mutex, 0, FALSE); DosCreateEventSem(NULL, &event, 0, FALSE); }
/** * cairo_os2_surface_create: * @hps_client_window: the presentation handle to bind the surface to * @width: the width of the surface * @height: the height of the surface * * Create a Cairo surface which is bound to a given presentation space (HPS). * The caller retains ownership of the HPS and must dispose of it after the * the surface has been destroyed. The surface will be created to have the * given size. By default every change to the surface will be made visible * immediately by blitting it into the window. This can be changed with * cairo_os2_surface_set_manual_window_refresh(). * Note that the surface will contain garbage when created, so the pixels * have to be initialized by hand first. You can use the Cairo functions to * fill it with black, or use cairo_surface_mark_dirty() to fill the surface * with pixels from the window/HPS. * * Return value: the newly created surface * * Since: 1.4 **/ cairo_surface_t * cairo_os2_surface_create (HPS hps_client_window, int width, int height) { cairo_os2_surface_t *local_os2_surface = 0; cairo_status_t status; int rc; /* Check the size of the window */ if ((width <= 0) || (height <= 0)) { status = _cairo_error (CAIRO_STATUS_INVALID_SIZE); goto error_exit; } /* Allocate an OS/2 surface structure. */ local_os2_surface = (cairo_os2_surface_t *) malloc (sizeof (cairo_os2_surface_t)); if (!local_os2_surface) { status = _cairo_error (CAIRO_STATUS_NO_MEMORY); goto error_exit; } memset(local_os2_surface, 0, sizeof(cairo_os2_surface_t)); /* Allocate resources: mutex & event semaphores and the pixel buffer */ if (DosCreateMutexSem (NULL, &(local_os2_surface->hmtx_use_private_fields), 0, FALSE)) { status = _cairo_error (CAIRO_STATUS_DEVICE_ERROR); goto error_exit; } if (DosCreateEventSem (NULL, &(local_os2_surface->hev_pixel_array_came_back), 0, FALSE)) { status = _cairo_error (CAIRO_STATUS_DEVICE_ERROR); goto error_exit; } local_os2_surface->pixels = (unsigned char *) _buffer_alloc (height, width, 4); if (!local_os2_surface->pixels) { status = _cairo_error (CAIRO_STATUS_NO_MEMORY); goto error_exit; } /* Create image surface from pixel array */ local_os2_surface->image_surface = (cairo_image_surface_t *) cairo_image_surface_create_for_data (local_os2_surface->pixels, CAIRO_FORMAT_ARGB32, width, /* Width */ height, /* Height */ width * 4); /* Rowstride */ status = local_os2_surface->image_surface->base.status; if (status) goto error_exit; /* Set values for OS/2-specific data that aren't zero/NULL/FALSE. * Note: hps_client_window may be null if this was called by * cairo_os2_surface_create_for_window(). */ local_os2_surface->hps_client_window = hps_client_window; local_os2_surface->blit_as_changes = TRUE; /* Prepare BITMAPINFO2 structure for our buffer */ local_os2_surface->bitmap_info.cbFix = sizeof (BITMAPINFOHEADER2); local_os2_surface->bitmap_info.cx = width; local_os2_surface->bitmap_info.cy = height; local_os2_surface->bitmap_info.cPlanes = 1; local_os2_surface->bitmap_info.cBitCount = 32; /* Initialize base surface */ _cairo_surface_init (&local_os2_surface->base, &cairo_os2_surface_backend, NULL, /* device */ _cairo_content_from_format (CAIRO_FORMAT_ARGB32)); /* Successful exit */ return (cairo_surface_t *)local_os2_surface; error_exit: /* This point will only be reached if an error occurred */ if (local_os2_surface) { if (local_os2_surface->pixels) _buffer_free (local_os2_surface->pixels); if (local_os2_surface->hev_pixel_array_came_back) DosCloseEventSem (local_os2_surface->hev_pixel_array_came_back); if (local_os2_surface->hmtx_use_private_fields) DosCloseMutexSem (local_os2_surface->hmtx_use_private_fields); free (local_os2_surface); } return _cairo_surface_create_in_error (status); }
APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, apr_file_t **out, apr_pool_t *pool) { ULONG filedes[2]; ULONG rc, action; static int id = 0; char pipename[50]; sprintf(pipename, "/pipe/%d.%d", getpid(), id++); rc = DosCreateNPipe(pipename, filedes, NP_ACCESS_INBOUND, NP_NOWAIT|1, 4096, 4096, 0); if (rc) return APR_FROM_OS_ERROR(rc); rc = DosConnectNPipe(filedes[0]); if (rc && rc != ERROR_PIPE_NOT_CONNECTED) { DosClose(filedes[0]); return APR_FROM_OS_ERROR(rc); } rc = DosOpen (pipename, filedes+1, &action, 0, FILE_NORMAL, OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW, OPEN_ACCESS_WRITEONLY | OPEN_SHARE_DENYREADWRITE, NULL); if (rc) { DosClose(filedes[0]); return APR_FROM_OS_ERROR(rc); } (*in) = (apr_file_t *)apr_palloc(pool, sizeof(apr_file_t)); rc = DosCreateEventSem(NULL, &(*in)->pipeSem, DC_SEM_SHARED, FALSE); if (rc) { DosClose(filedes[0]); DosClose(filedes[1]); return APR_FROM_OS_ERROR(rc); } rc = DosSetNPipeSem(filedes[0], (HSEM)(*in)->pipeSem, 1); if (!rc) { rc = DosSetNPHState(filedes[0], NP_WAIT); } if (rc) { DosClose(filedes[0]); DosClose(filedes[1]); DosCloseEventSem((*in)->pipeSem); return APR_FROM_OS_ERROR(rc); } (*in)->pool = pool; (*in)->filedes = filedes[0]; (*in)->fname = apr_pstrdup(pool, pipename); (*in)->isopen = TRUE; (*in)->buffered = FALSE; (*in)->flags = APR_FOPEN_READ; (*in)->pipe = 1; (*in)->timeout = -1; (*in)->blocking = BLK_ON; (*in)->ungetchar = -1; apr_pool_cleanup_register(pool, *in, apr_file_cleanup, apr_pool_cleanup_null); (*out) = (apr_file_t *)apr_palloc(pool, sizeof(apr_file_t)); rc = DosCreateEventSem(NULL, &(*out)->pipeSem, DC_SEM_SHARED, FALSE); if (rc) { DosClose(filedes[0]); DosClose(filedes[1]); DosCloseEventSem((*in)->pipeSem); return APR_FROM_OS_ERROR(rc); } rc = DosSetNPipeSem(filedes[1], (HSEM)(*out)->pipeSem, 1); if (rc) { DosClose(filedes[0]); DosClose(filedes[1]); DosCloseEventSem((*in)->pipeSem); DosCloseEventSem((*out)->pipeSem); return APR_FROM_OS_ERROR(rc); } (*out)->pool = pool; (*out)->filedes = filedes[1]; (*out)->fname = apr_pstrdup(pool, pipename); (*out)->isopen = TRUE; (*out)->buffered = FALSE; (*out)->flags = APR_FOPEN_WRITE; (*out)->pipe = 1; (*out)->timeout = -1; (*out)->blocking = BLK_ON; (*out)->ungetchar = -1; apr_pool_cleanup_register(pool, *out, apr_file_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; }
int DART_OpenAudio(_THIS, SDL_AudioSpec *spec) { Uint16 test_format = SDL_FirstAudioFormat(spec->format); int valid_datatype = 0; MCI_AMP_OPEN_PARMS AmpOpenParms; MCI_GENERIC_PARMS GenericParms; int iDeviceOrd = 0; int bOpenShared = 1; int iBits = 16; int iFreq = 44100; int iChannels = 2; int iNumBufs = 2; int iBufSize; int iOpenMode; int iSilence; int rc; SDL_memset(&AmpOpenParms, 0, sizeof(MCI_AMP_OPEN_PARMS)); AmpOpenParms.pszDeviceType = (PSZ) (MCI_DEVTYPE_AUDIO_AMPMIX | (iDeviceOrd << 16)); iOpenMode = MCI_WAIT | MCI_OPEN_TYPE_ID; if (bOpenShared) iOpenMode |= MCI_OPEN_SHAREABLE; rc = mciSendCommand( 0, MCI_OPEN, iOpenMode, (PVOID) &AmpOpenParms, 0); if (rc!=MCIERR_SUCCESS) return (-1); iDeviceOrd = AmpOpenParms.usDeviceID; if (spec->channels > 2) spec->channels = 2; while ((!valid_datatype) && (test_format)) { spec->format = test_format; valid_datatype = 1; switch (test_format) { case AUDIO_U8: iSilence = 0x80; iBits = 8; break; case AUDIO_S16LSB: iSilence = 0x00; iBits = 16; break; default: valid_datatype = 0; test_format = SDL_NextAudioFormat(); break; } } if (!valid_datatype) { mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("Unsupported audio format"); return (-1); } iFreq = spec->freq; iChannels = spec->channels; SDL_CalculateAudioSpec(spec); iBufSize = spec->size; SDL_memset(&(_this->hidden->MixSetupParms), 0, sizeof(MCI_MIXSETUP_PARMS)); _this->hidden->MixSetupParms.ulBitsPerSample = iBits; _this->hidden->MixSetupParms.ulFormatTag = MCI_WAVE_FORMAT_PCM; _this->hidden->MixSetupParms.ulSamplesPerSec = iFreq; _this->hidden->MixSetupParms.ulChannels = iChannels; _this->hidden->MixSetupParms.ulFormatMode = MCI_PLAY; _this->hidden->MixSetupParms.ulDeviceType = MCI_DEVTYPE_WAVEFORM_AUDIO; _this->hidden->MixSetupParms.pmixEvent = DARTEventFunc; rc = mciSendCommand (iDeviceOrd, MCI_MIXSETUP, MCI_WAIT | MCI_MIXSETUP_QUERYMODE, &(_this->hidden->MixSetupParms), 0); if (rc!=MCIERR_SUCCESS) { mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("Audio device doesn't support requested audio format"); return(-1); } rc = mciSendCommand(iDeviceOrd, MCI_MIXSETUP, MCI_WAIT | MCI_MIXSETUP_INIT, &(_this->hidden->MixSetupParms), 0); if (rc!=MCIERR_SUCCESS) { mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("Audio device could not be set up"); return(-1); } _this->hidden->pMixBuffers = (MCI_MIX_BUFFER *) SDL_malloc(sizeof(MCI_MIX_BUFFER)*iNumBufs); if (!(_this->hidden->pMixBuffers)) { mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("Not enough memory for audio buffer descriptors"); return(-1); } _this->hidden->BufferParms.ulNumBuffers = iNumBufs; _this->hidden->BufferParms.ulBufferSize = iBufSize; _this->hidden->BufferParms.pBufList = _this->hidden->pMixBuffers; rc = mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_ALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0); if ((rc!=MCIERR_SUCCESS) || (iNumBufs != _this->hidden->BufferParms.ulNumBuffers) || (_this->hidden->BufferParms.ulBufferSize==0)) { SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL; mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("DART could not allocate buffers"); return(-1); } { int i; for (i=0; i<iNumBufs; i++) { pMixBufferDesc pBufferDesc = (pMixBufferDesc) SDL_malloc(sizeof(tMixBufferDesc));; if ((!(_this->hidden->pMixBuffers[i].pBuffer)) || (!pBufferDesc)) { { int j; for (j=0; j<i; j++) SDL_free((void *)(_this->hidden->pMixBuffers[j].ulUserParm)); } mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0); SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL; mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("Error at internal buffer check"); return(-1); } pBufferDesc->iBufferUsage = BUFFER_EMPTY; pBufferDesc->pSDLAudioDevice = _this; _this->hidden->pMixBuffers[i].ulBufferLength = _this->hidden->BufferParms.ulBufferSize; _this->hidden->pMixBuffers[i].ulUserParm = (ULONG) pBufferDesc; _this->hidden->pMixBuffers[i].ulFlags = 0; SDL_memset(_this->hidden->pMixBuffers[i].pBuffer, iSilence, iBufSize); } } _this->hidden->iNextFreeBuffer = 0; _this->hidden->iLastPlayedBuf = -1; if (DosCreateEventSem(NULL, &(_this->hidden->hevAudioBufferPlayed), 0, FALSE)!=NO_ERROR) { { int i; for (i=0; i<iNumBufs; i++) SDL_free((void *)(_this->hidden->pMixBuffers[i].ulUserParm)); } mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_DEALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0); SDL_free(_this->hidden->pMixBuffers); _this->hidden->pMixBuffers = NULL; mciSendCommand(iDeviceOrd, MCI_CLOSE, MCI_WAIT, &GenericParms, 0); SDL_SetError("Could not create event semaphore"); return(-1); } _this->hidden->iCurrDeviceOrd = iDeviceOrd; _this->hidden->iCurrFreq = iFreq; _this->hidden->iCurrBits = iBits; _this->hidden->iCurrChannels = iChannels; _this->hidden->iCurrNumBufs = iNumBufs; _this->hidden->iCurrBufSize = iBufSize; return (0); }
int open_os2(audio_output_t *ao) { ULONG rc,i; char *temp; ULONG openflags; PPIB ppib; USHORT bits; if(maop.usDeviceID) return (maop.usDeviceID); if(!ai) return -1; if(!ao->device) ao->device = "0"; if(ao->rate < 0) ao->rate = 44100; if(ao->channels < 0) ao->channels = 2; if(ao->format < 0) ao->format = MPG123_ENC_SIGNED_16; if(ao->format == MPG123_ENC_SIGNED_16) bits = 16; else if(ao->format == MPG123_ENC_UNSIGNED_8) bits = 8; else return -1; /* open the mixer device */ memset (&maop, 0, sizeof(maop)); maop.usDeviceID = 0; maop.pszDeviceType = (PSZ) MAKEULONG(MCI_DEVTYPE_AUDIO_AMPMIX, atoi(ao->device)); openflags = MCI_WAIT | MCI_OPEN_TYPE_ID; if(!lockdevice) openflags |= MCI_OPEN_SHAREABLE; rc = mciSendCommand(0, MCI_OPEN, openflags, &maop, 0); if (ULONG_LOWD(rc) != MCIERR_SUCCESS) { MciError(rc); maop.usDeviceID = 0; return(-1); } /* volume in ao->gain ?? */ /* Set the MCI_MIXSETUP_PARMS data structure to match the audio stream. */ memset(&mmp, 0, sizeof(mmp)); mmp.ulBitsPerSample = bits; mmp.ulFormatTag = MCI_WAVE_FORMAT_PCM; mmp.ulSamplesPerSec = ao->rate; mmp.ulChannels = ao->channels; /* Setup the mixer for playback of wave data */ mmp.ulFormatMode = MCI_PLAY; mmp.ulDeviceType = MCI_DEVTYPE_WAVEFORM_AUDIO; mmp.pmixEvent = DARTEvent; rc = mciSendCommand( maop.usDeviceID, MCI_MIXSETUP, MCI_WAIT | MCI_MIXSETUP_INIT, &mmp, 0 ); if ( ULONG_LOWD(rc) != MCIERR_SUCCESS ) { MciError(rc); maop.usDeviceID = 0; return(-1); } volume = audio_set_volume(ai,volume); /* Set up the BufferParms data structure and allocate * device buffers from the Amp-Mixer */ memset(&mbp, 0, sizeof(mbp)); free(MixBuffers); free(bufferinfo); if(numbuffers < 5) numbuffers = 5; if(numbuffers > 200) numbuffers = 200; MixBuffers = calloc(numbuffers, sizeof(*MixBuffers)); bufferinfo = calloc(numbuffers, sizeof(*bufferinfo)); ulMCIBuffers = numbuffers; mbp.ulNumBuffers = ulMCIBuffers; /* mbp.ulBufferSize = mmp.ulBufferSize; */ /* I don't like this... they must be smaller than 64KB or else the engine needs major rewrite */ mbp.ulBufferSize = audiobufsize; mbp.pBufList = MixBuffers; rc = mciSendCommand( maop.usDeviceID, MCI_BUFFER, MCI_WAIT | MCI_ALLOCATE_MEMORY, (PVOID) &mbp, 0 ); if ( ULONG_LOWD(rc) != MCIERR_SUCCESS ) { MciError(rc); maop.usDeviceID = 0; return(-1); } pBufferplayed = playedbuffer.pBuffer = calloc(1,audiobufsize); ulMCIBuffers = mbp.ulNumBuffers; /* never know! */ /* Fill all device buffers with zeros and set linked list */ for(i = 0; i < ulMCIBuffers; i++) { MixBuffers[i].ulFlags = 0; MixBuffers[i].ulBufferLength = mbp.ulBufferSize; memset(MixBuffers[i].pBuffer, 0, MixBuffers[i].ulBufferLength); MixBuffers[i].ulUserParm = (ULONG) &bufferinfo[i]; bufferinfo[i].NextBuffer = &MixBuffers[i+1]; } bufferinfo[i-1].NextBuffer = &MixBuffers[0]; /* Create a semaphore to know when data has been played by the DART thread */ DosCreateEventSem(NULL,&dataplayed,0,FALSE); playingbuffer = &MixBuffers[0]; tobefilled = &MixBuffers[1]; playingframe = 0; nomoredata = TRUE; nobuffermode = FALSE; justflushed = FALSE; if(boostprio) { temp = alloca(strlen(boostprio)+1); strcpy(temp,boostprio); boostdelta = atoi(temp+1); *(temp+1) = 0; boostclass = atoi(temp); } if(boostclass > 4) boostdelta = 3; if(boostdelta > 31) boostdelta = 31; if(boostdelta < -31) boostdelta = -31; if(normalprio) { temp = alloca(strlen(normalprio)+1); strcpy(temp,normalprio); normaldelta = atoi(temp+1); *(temp+1) = 0; normalclass = atoi(temp); } if(normalclass > 4) normaldelta = 3; if(normaldelta > 31) normaldelta = 31; if(normaldelta < -31) normaldelta = -31; DosGetInfoBlocks(&mainthread,&ppib); /* ppib not needed, but makes some DOSCALLS.DLL crash */ DosSetPriority(PRTYS_THREAD,boostclass,boostdelta,mainthread->tib_ptib2->tib2_ultid); /* Write buffers to kick off the amp mixer. see DARTEvent() */ rc = mmp.pmixWrite( mmp.ulMixHandle, MixBuffers, ulMCIBuffers ); return maop.usDeviceID; }
static int DART_OpenDevice(_THIS, const char *devname, int iscapture) { SDL_AudioFormat test_format = SDL_FirstAudioFormat(_this->spec.format); int valid_datatype = 0; MCI_AMP_OPEN_PARMS AmpOpenParms; int iDeviceOrd = 0; // Default device to be used int bOpenShared = 1; // Try opening it shared int iBits = 16; // Default is 16 bits signed int iFreq = 44100; // Default is 44KHz int iChannels = 2; // Default is 2 channels (Stereo) int iNumBufs = 2; // Number of audio buffers: 2 int iBufSize; int iOpenMode; int iSilence; int rc; /* Initialize all variables that we clean on shutdown */ _this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *_this->hidden)); if (_this->hidden == NULL) { SDL_OutOfMemory(); return 0; } SDL_memset(_this->hidden, 0, (sizeof *_this->hidden)); // First thing is to try to open a given DART device! SDL_memset(&AmpOpenParms, 0, sizeof(MCI_AMP_OPEN_PARMS)); // pszDeviceType should contain the device type in low word, and device ordinal in high word! AmpOpenParms.pszDeviceType = (PSZ) (MCI_DEVTYPE_AUDIO_AMPMIX | (iDeviceOrd << 16)); iOpenMode = MCI_WAIT | MCI_OPEN_TYPE_ID; if (bOpenShared) iOpenMode |= MCI_OPEN_SHAREABLE; rc = mciSendCommand(0, MCI_OPEN, iOpenMode, (PVOID) & AmpOpenParms, 0); if (rc != MCIERR_SUCCESS) { // No audio available?? DART_CloseDevice(_this); SDL_SetError("DART: Couldn't open audio device."); return 0; } // Save the device ID we got from DART! // We will use this in the next calls! _this->hidden->iCurrDeviceOrd = iDeviceOrd = AmpOpenParms.usDeviceID; // Determine the audio parameters from the AudioSpec if (_this->spec.channels > 4) _this->spec.channels = 4; while ((!valid_datatype) && (test_format)) { _this->spec.format = test_format; valid_datatype = 1; switch (test_format) { case AUDIO_U8: // Unsigned 8 bit audio data iSilence = 0x80; _this->hidden->iCurrBits = iBits = 8; break; case AUDIO_S16LSB: // Signed 16 bit audio data iSilence = 0x00; _this->hidden->iCurrBits = iBits = 16; break; // !!! FIXME: int32? default: valid_datatype = 0; test_format = SDL_NextAudioFormat(); break; } } if (!valid_datatype) { // shouldn't happen, but just in case... // Close DART, and exit with error code! DART_CloseDevice(_this); SDL_SetError("Unsupported audio format"); return 0; } _this->hidden->iCurrFreq = iFreq = _this->spec.freq; _this->hidden->iCurrChannels = iChannels = _this->spec.channels; /* Update the fragment size as size in bytes */ SDL_CalculateAudioSpec(&_this->spec); _this->hidden->iCurrBufSize = iBufSize = _this->spec.size; // Now query this device if it supports the given freq/bits/channels! SDL_memset(&(_this->hidden->MixSetupParms), 0, sizeof(MCI_MIXSETUP_PARMS)); _this->hidden->MixSetupParms.ulBitsPerSample = iBits; _this->hidden->MixSetupParms.ulFormatTag = MCI_WAVE_FORMAT_PCM; _this->hidden->MixSetupParms.ulSamplesPerSec = iFreq; _this->hidden->MixSetupParms.ulChannels = iChannels; _this->hidden->MixSetupParms.ulFormatMode = MCI_PLAY; _this->hidden->MixSetupParms.ulDeviceType = MCI_DEVTYPE_WAVEFORM_AUDIO; _this->hidden->MixSetupParms.pmixEvent = DARTEventFunc; rc = mciSendCommand(iDeviceOrd, MCI_MIXSETUP, MCI_WAIT | MCI_MIXSETUP_QUERYMODE, &(_this->hidden->MixSetupParms), 0); if (rc != MCIERR_SUCCESS) { // The device cannot handle this format! // Close DART, and exit with error code! DART_CloseDevice(_this); SDL_SetError("Audio device doesn't support requested audio format"); return 0; } // The device can handle this format, so initialize! rc = mciSendCommand(iDeviceOrd, MCI_MIXSETUP, MCI_WAIT | MCI_MIXSETUP_INIT, &(_this->hidden->MixSetupParms), 0); if (rc != MCIERR_SUCCESS) { // The device could not be opened! // Close DART, and exit with error code! DART_CloseDevice(_this); SDL_SetError("Audio device could not be set up"); return 0; } // Ok, the device is initialized. // Now we should allocate buffers. For this, we need a place where // the buffer descriptors will be: _this->hidden->pMixBuffers = (MCI_MIX_BUFFER *) SDL_malloc(sizeof(MCI_MIX_BUFFER) * iNumBufs); if (!(_this->hidden->pMixBuffers)) { // Not enough memory! // Close DART, and exit with error code! DART_CloseDevice(_this); SDL_OutOfMemory(); return 0; } // Now that we have the place for buffer list, we can ask DART for the // buffers! _this->hidden->BufferParms.ulNumBuffers = iNumBufs; // Number of buffers _this->hidden->BufferParms.ulBufferSize = iBufSize; // each with this size _this->hidden->BufferParms.pBufList = _this->hidden->pMixBuffers; // getting descriptorts into this list // Allocate buffers! rc = mciSendCommand(iDeviceOrd, MCI_BUFFER, MCI_WAIT | MCI_ALLOCATE_MEMORY, &(_this->hidden->BufferParms), 0); if ((rc != MCIERR_SUCCESS) || (iNumBufs != _this->hidden->BufferParms.ulNumBuffers) || (_this->hidden->BufferParms.ulBufferSize == 0)) { // Could not allocate memory! // Close DART, and exit with error code! DART_CloseDevice(_this); SDL_SetError("DART could not allocate buffers"); return 0; } _this->hidden->iCurrNumBufs = iNumBufs; // Ok, we have all the buffers allocated, let's mark them! { int i; for (i = 0; i < iNumBufs; i++) { pMixBufferDesc pBufferDesc = (pMixBufferDesc) SDL_malloc(sizeof(tMixBufferDesc));; // Check if this buffer was really allocated by DART if ((!(_this->hidden->pMixBuffers[i].pBuffer)) || (!pBufferDesc)) { // Wrong buffer! DART_CloseDevice(_this); SDL_SetError("Error at internal buffer check"); return 0; } pBufferDesc->iBufferUsage = BUFFER_EMPTY; pBufferDesc->pSDLAudioDevice = _this; _this->hidden->pMixBuffers[i].ulBufferLength = _this->hidden->BufferParms.ulBufferSize; _this->hidden->pMixBuffers[i].ulUserParm = (ULONG) pBufferDesc; // User parameter: Description of buffer _this->hidden->pMixBuffers[i].ulFlags = 0; // Some stuff should be flagged here for DART, like end of // audio data, but as we will continously send // audio data, there will be no end.:) SDL_memset(_this->hidden->pMixBuffers[i].pBuffer, iSilence, iBufSize); } } _this->hidden->iNextFreeBuffer = 0; _this->hidden->iLastPlayedBuf = -1; // Create event semaphore if (DosCreateEventSem (NULL, &(_this->hidden->hevAudioBufferPlayed), 0, FALSE) != NO_ERROR) { DART_CloseDevice(_this); SDL_SetError("Could not create event semaphore"); return 0; } return 1; }
int main( void ) { unsigned long action; char buffer[32]; struct messagequeue chtmsgq; struct clienthandlerthreadparameters chtp; unsigned long count; struct connectthreadparameters ctp; HFILE hfcon; HFILE hfstdout; struct message * msg; APIRET rc; int running; /* Reopen file 1 in case the user has redirected output. */ DosOpen( "CON", &hfcon, &action, 0, FILE_NORMAL, OPEN_ACTION_FAIL_IF_NEW|OPEN_ACTION_OPEN_IF_EXISTS, OPEN_FLAGS_FAIL_ON_ERROR|OPEN_FLAGS_SEQUENTIAL| OPEN_SHARE_DENYNONE|OPEN_ACCESS_WRITEONLY, NULL ); hfstdout = HFILE_STDOUT; DosDupHandle(hfcon,&hfstdout); /* Unbuffer stdout. */ setbuf(stdout,NULL); /* Header stuff. */ printf("tserver v%d.%03d Client/Server Demonstration Server\n", TSERVER_VERSION,TSERVER_PATCHLEVEL); /* Install break handlers to catch ^C and Ctrl-Break. */ signal(SIGINT,sigbreak); signal(SIGBREAK,sigbreak); /* Begin application initialization ... */ printf("Server is initializing - please wait ... "); /* Initialize mainmsgq. */ DosCreateMutexSem(NULL,&mainmsgq.access,0,FALSE); mainmsgq.q = NULL; mainmsgq.qtail = &mainmsgq.q; DosCreateEventSem(NULL,&mainmsgq.available,0,FALSE); /* Start the connect thread. */ DosCreateEventSem(NULL,&ctp.initialized,0,FALSE); ctp.maxpipes = ( unsigned char ) NP_UNLIMITED_INSTANCES; ctp.pipename = "\\pipe\\time"; DosCreateEventSem(NULL,&ctp.shutdown,0,FALSE); ctp.msgq = &mainmsgq; DosCreateEventSem(NULL,&ctp.terminated,0,FALSE); _beginthread( connectthread, NULL, 8192, ( void * ) &ctp ); DosWaitEventSem(ctp.initialized,SEM_INDEFINITE_WAIT); DosCloseEventSem(ctp.initialized); /* Start the client handler thread. */ DosCreateMutexSem(NULL,&chtmsgq.access,0,FALSE); chtmsgq.q = NULL; chtmsgq.qtail = &chtmsgq.q; DosCreateEventSem(NULL,&chtmsgq.available,0,FALSE); DosCreateEventSem(NULL,&chtp.initialized,0,FALSE); chtp.inmsgq = &chtmsgq; chtp.outmsgq = &mainmsgq; DosCreateEventSem(NULL,&chtp.terminated,0,FALSE); _beginthread( clienthandlerthread, NULL, 8192, ( void * ) &chtp ); DosWaitEventSem(chtp.initialized,SEM_INDEFINITE_WAIT); DosCloseEventSem(chtp.initialized); printf("completed\n\n"); /* Initialization completed. */ printf( "%s Server is running.\n", timestamp(buffer) ); running = !0; while ( running ) { printf( "\r%s ", timestamp(buffer) ); /* Wait one second for a message to hit the queue. If one ** ** arrives, handle it, otherwise just update the timer. */ rc = DosWaitEventSem(mainmsgq.available,1000); if ( rc != ERROR_TIMEOUT ) /* Loop until message queue is empty ( break below ). */ while ( !0 ) { DosRequestMutexSem(mainmsgq.access,SEM_INDEFINITE_WAIT); msg = mainmsgq.q; if ( msg != NULL ) { mainmsgq.q = msg->next; /* If last message dequeued, reset tail pointer. */ if ( mainmsgq.q == NULL ) mainmsgq.qtail = &mainmsgq.q; } DosResetEventSem(mainmsgq.available,&count); DosReleaseMutexSem(mainmsgq.access); /* Break out of inner loop if last message pulled. */ if ( msg == NULL ) break; /* Update the timer ... */ printf( "\r%s ", timestamp(buffer) ); switch ( msg->id ) { case closed: /* Client disconnected. */ printf("Closed pipe %lu.\n", msg->data.closeddata.hpipe); break; case connected: /* Client connected. Display message, then ** ** pass the pipe handle to the client handler. */ printf("Connected pipe %lu.\n", msg->data.connecteddata.hpipe); DosRequestMutexSem(chtmsgq.access, SEM_INDEFINITE_WAIT); *chtmsgq.qtail = malloc( sizeof( struct message ) ); (*chtmsgq.qtail)->id = connected; (*chtmsgq.qtail)->data.connecteddata.hpipe = msg->data.connecteddata.hpipe; (*chtmsgq.qtail)->next = NULL; DosPostEventSem(chtmsgq.available); DosReleaseMutexSem(chtmsgq.access); break; case ctclosed: /* Connect thread has shut down prematurely. ** ** This will occur if there is an error in ** ** that thread. */ printf( "Connect thread died - NO NEW CLIENTS MAY " "CONNECT.\n"); break; case cterror: /* Display error message from the connect ** ** thread. */ if ( msg->data.cterrordata.ec == pipedisconnected ) printf("Disconnected from pipe %lu.\n", msg->data.cterrordata.hpipe); else printf("Error %d in connect thread.\n", msg->data.cterrordata.ec); break; case executing: /* Log informative message. */ printf("Pipe %d executing: %s.\n", msg->data.executingdata.hpipe, msg->data.executingdata.cmd); break; case shutdownreq: printf("Shutting down.\n"); running = 0; break; case breakhit: printf("**** break ****\n"); running = 0; break; } free(msg); } } /* Begin termination ... */ printf("\nServer is shutting down - please wait ... "); /* Post shutdown message to client handler thread. */ DosRequestMutexSem(chtmsgq.access,SEM_INDEFINITE_WAIT); *chtmsgq.qtail = malloc( sizeof( struct message ) ); (*chtmsgq.qtail)->id = shutdownreq; (*chtmsgq.qtail)->next = NULL; DosPostEventSem(chtmsgq.available); DosReleaseMutexSem(chtmsgq.access); DosWaitEventSem(chtp.terminated,SEM_INDEFINITE_WAIT); DosCloseEventSem(chtp.terminated); /* Clear out any messages remaining in the queue. */ while ( chtmsgq.q != NULL ) { msg = chtmsgq.q; chtmsgq.q = msg->next; free(msg); } DosCloseEventSem(chtmsgq.available); DosCloseMutexSem(chtmsgq.access); /* Post shutdown semaphore in connect thread. */ DosPostEventSem(ctp.shutdown); DosWaitEventSem(ctp.terminated,SEM_INDEFINITE_WAIT); DosCloseEventSem(ctp.shutdown); DosCloseEventSem(ctp.terminated); /* All threads shut down. Clear out the main message queue. */ while ( mainmsgq.q != NULL ) { msg = mainmsgq.q; mainmsgq.q = msg->next; free(msg); } DosCloseEventSem(mainmsgq.available); DosCloseMutexSem(mainmsgq.access); printf("completed\n"); /* Outta here ... */ return 0; }
int main (int argc, char *argv[]) { APIRET rc; PCHAR pcEnv; PRFPROFILE prfProfile; #ifdef DEBUG ulDebugMask = 0xFFFFFFFF; #endif /* DEBUG */ hab = WinInitialize(0); hmq = WinCreateMsgQueue(hab, 0); DebugS (1, "PM Interface initialized"); /* Shared Memory organisieren */ if (rc = DosGetNamedSharedMem ((PPVOID) &pShareInitOS2, SHARE_INITOS2, PAG_READ | PAG_WRITE)) { if (rc = DosAllocSharedMem( (PPVOID) &pShareInitOS2, // Pointer to shared mem SHARE_INITOS2, // Name CCHSHARE_INITOS2, // Size of shared mem PAG_COMMIT | PAG_READ | PAG_WRITE)) // Flags return(1); else { /* Shared Memory initialisieren */ memset (pShareInitOS2, '\0', CCHSHARE_INITOS2); pShareInitOS2->pszRegFile = (PCHAR) pShareInitOS2 + sizeof(*pShareInitOS2); strcpy (pShareInitOS2->pszRegFile, DosScanEnv (ENV_SYSTEM_INI, &pcEnv) ? "" : pcEnv); pShareInitOS2->pszRootUserIni = pShareInitOS2->pszRegFile + strlen(pShareInitOS2->pszRegFile) + 1; pShareInitOS2->pszRootSystemIni = pShareInitOS2->pszRootUserIni + 1; pShareInitOS2->pszUserIni = pShareInitOS2->pszRootSystemIni + 1; pShareInitOS2->pszSystemIni = pShareInitOS2->pszUserIni + CCHMAXPATH; pShareInitOS2->pszEnvironment = pShareInitOS2->pszSystemIni + CCHMAXPATH; } } DebugS (1, "Shared Memory initialized"); /* Semaphoren organisieren */ rc = DosOpenEventSem (HEV_SAMMY, &hevSammy); if( rc ) rc = DosCreateEventSem( HEV_SAMMY, // Name &hevSammy, // Pointer to sem 0, // Not used with named sems FALSE); // Initial state (FALSE = SET) else /* Sammy ist bereits installiert */ { pShareInitOS2->pszEnvironment[0] = '\0'; pShareInitOS2->pszEnvironment[1] = '\0'; pShareInitOS2->pszSystemIni[0] = '\0'; pShareInitOS2->pszUserIni[0] = '\0'; DosPostEventSem(hevSammy); goto Exit; } if( rc ) { intSammyRetCode = rc; goto Exit; } rc = DosOpenEventSem (HEV_PRFRESETLOCK, &hevPrfResetLock); if( rc ) rc = DosCreateEventSem( HEV_PRFRESETLOCK, // Name &hevPrfResetLock, // Pointer to sem 0, // Not used with named sems TRUE); // Initial state (TRUE = POSTED) if( rc ) { intSammyRetCode = rc; goto Exit; } DebugS (1, "Semaphores initialized"); ChangeWPS(pShareInitOS2->pszUserIni, pShareInitOS2->pszSystemIni); /* Hintergrundloop starten, das Shell mit aktueller Env. startet */ DosCreateThread (&tid1, (PFNTHREAD) thStartProg, (ULONG) ((argc > 1) ? argv[1] : ""), 0, THREADSTACK); DebugS (1, "Background loop started"); /* Hintergrundloop starten, das jeweils nach L�schen einer Semaphore */ /* einen prfReset initiiert */ DosCreateThread (&tid2, (PFNTHREAD) thSwitch, (ULONG) 0, 0, THREADSTACK); while (WinGetMsg (hab, &qmsg, 0, 0, 0)) WinDispatchMsg (hab, &qmsg); if (intSammyRetCode) { DosKillThread (tid1); DosKillThread (tid2); WinSetObjectData(WinQueryObject("<WP_DESKTOP>"), "WORKAREA=NO"); WinPostMsg(WinQueryWindow(HWND_DESKTOP, QW_BOTTOM), WM_CLOSE, 0, 0); WinAlarm (HWND_DESKTOP, WA_ERROR); prfProfile.pszSysName = (DosScanEnv (ENV_SYSTEM_INI, &pcEnv) ? "" : pcEnv); prfProfile.pszUserName = (DosScanEnv (ENV_USER_INI, &pcEnv) ? "" : pcEnv); prfProfile.cchUserName = strlen(prfProfile.pszUserName); prfProfile.cchSysName = strlen(prfProfile.pszSysName); DosSleep (1000); DosKillProcess( DKP_PROCESSTREE, ulShellID ); if ( !PrfReset(hab, &prfProfile)) WinSetObjectData(WinQueryObject("<WP_DESKTOP>"), "OPEN=ICON;WORKAREA=YES"); } Exit: WinDestroyMsgQueue(hmq); WinTerminate(hab); DebugS (1, "Application terminated"); return intSammyRetCode; }
int main(int argc, char **argv) #endif { int i; #ifdef LINUXVGA LINUX_setup(); /* setup VGA before dropping privilege DBT 4/5/99 */ drop_privilege(); #endif /* make sure that we really have revoked root access, this might happen if gnuplot is compiled without vga support but is installed suid by mistake */ #ifdef __linux__ setuid(getuid()); #endif #if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__) PC_setup(); #endif /* MSDOS !Windows */ /* HBB: Seems this isn't needed any more for DJGPP V2? */ /* HBB: disable all floating point exceptions, just keep running... */ #if defined(DJGPP) && (DJGPP!=2) _control87(MCW_EM, MCW_EM); #endif #if defined(OS2) int rc; #ifdef OS2_IPC char semInputReadyName[40]; sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() ); rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0); if (rc != 0) fputs("DosCreateEventSem error\n",stderr); #endif rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL); #endif /* malloc large blocks, otherwise problems with fragmented mem */ #ifdef MALLOCDEBUG malloc_debug(7); #endif /* get helpfile from home directory */ #ifdef __DJGPP__ { char *s; strcpy(HelpFile, argv[0]); for (s = HelpFile; *s; s++) if (*s == DIRSEP1) *s = DIRSEP2; /* '\\' to '/' */ strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih"); } /* Add also some "paranoid" tests for '\\': AP */ #endif /* DJGPP */ #ifdef VMS unsigned int status[2] = { 1, 0 }; #endif #if defined(HAVE_LIBEDITLINE) rl_getc_function = getc_wrapper; #endif #if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE) /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name. * It is used to parse a 'gnuplot' specific section in '~/.inputrc' * or gnuplot specific commands in '.editrc' (when using editline * instead of readline) */ rl_readline_name = "Gnuplot"; rl_terminal_name = getenv("TERM"); using_history(); #endif #if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION) rl_complete_with_tilde_expansion = 1; #endif for (i = 1; i < argc; i++) { if (!argv[i]) continue; if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) { printf("gnuplot %s patchlevel %s\n", gnuplot_version, gnuplot_patchlevel); return 0; } else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { printf( "Usage: gnuplot [OPTION]... [FILE]\n" #ifdef X11 "for X11 options see 'help X11->command-line-options'\n" #endif " -V, --version\n" " -h, --help\n" " -p --persist\n" " -e \"command1; command2; ...\"\n" "gnuplot %s patchlevel %s\n" #ifdef DIST_CONTACT "Report bugs to "DIST_CONTACT"\n" " or %s\n", #else "Report bugs to %s\n", #endif gnuplot_version, gnuplot_patchlevel, bug_email); return 0; } else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")) { persist_cl = TRUE; } } #ifdef X11 /* the X11 terminal removes tokens that it recognizes from argv. */ { int n = X11_args(argc, argv); argv += n; argc -= n; } #endif setbuf(stderr, (char *) NULL); #ifdef HAVE_SETVBUF /* this was once setlinebuf(). Docs say this is * identical to setvbuf(,NULL,_IOLBF,0), but MS C * faults this (size out of range), so we try with * size of 1024 instead. [SAS/C does that, too. -lh] * Failing this, I propose we just make the call and * ignore the return : its probably not a big deal */ if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0) (void) fputs("Could not linebuffer stdout\n", stderr); #ifdef X11 /* This call used to be in x11.trm, with the following comment: * Multi-character inputs like escape sequences but also mouse-pasted * text got buffered and therefore didn't trigger the select() function * in X11_waitforinput(). Switching to unbuffered input solved this. * 23 Jan 2002 (joze) * But switching to unbuffered mode causes all characters in the input * buffer to be lost. So the only safe time to do it is on program entry. * The #ifdef X11 is probably unnecessary, but makes the change minimal. * Do any non-X platforms suffer from the same problem? * EAM - Jan 2004. */ setvbuf(stdin, (char *) NULL, _IONBF, 0); #endif #endif gpoutfile = stdout; /* Initialize pre-loaded user variables */ (void) Gcomplex(&udv_pi.udv_value, M_PI, 0.0); udv_NaN = add_udv_by_name("NaN"); (void) Gcomplex(&(udv_NaN->udv_value), not_a_number(), 0.0); udv_NaN->udv_undef = FALSE; init_memory(); interactive = FALSE; init_terminal(); /* can set term type if it likes */ push_terminal(0); /* remember the default terminal */ /* reset the terminal when exiting */ /* this is done through gp_atexit so that other terminal functions * can be registered to be executed before the terminal is reset. */ GP_ATEXIT(term_reset); # if defined(_Windows) && ! defined(WGP_CONSOLE) interactive = TRUE; # else interactive = isatty(fileno(stdin)); # endif if (argc > 1) interactive = noinputfiles = FALSE; else noinputfiles = TRUE; /* Need this before show_version is called for the first time */ #ifdef HAVE_SYS_UTSNAME_H { struct utsname uts; /* something is fundamentally wrong if this fails ... */ if (uname(&uts) > -1) { # ifdef _AIX strcpy(os_name, uts.sysname); sprintf(os_name, "%s.%s", uts.version, uts.release); # elif defined(SCO) strcpy(os_name, "SCO"); strcpy(os_rel, uts.release); # elif defined(DJGPP) if (!strncmp(uts.sysname, "??Un", 4)) /* don't print ??Unknow" */ strcpy(os_name, "Unknown"); else { strcpy(os_name, uts.sysname); strcpy(os_rel, uts.release); } # else strcpy(os_name, uts.sysname); strcpy(os_rel, uts.release); # ifdef OS2 if (!strchr(os_rel,'.')) /* write either "2.40" or "4.0", or empty -- don't print "OS/2 1" */ strcpy(os_rel, ""); # endif # endif } } #else /* ! HAVE_SYS_UTSNAME_H */ strcpy(os_name, OS); strcpy(os_rel, ""); #endif /* HAVE_SYS_UTSNAME_H */ if (interactive) show_version(stderr); else show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */ #ifdef WGP_CONSOLE #ifdef CONSOLE_SWITCH_CP if (cp_changed && interactive) { fprintf(stderr, "\ngnuplot changed the codepage of this console from %i to %i to\n" \ "match the graph window. Some characters might only display correctly\n" \ "if you change the font to a non-raster type.\n", cp_input, GetConsoleCP()); } #else if ((GetConsoleCP() != GetACP()) && interactive) { fprintf(stderr, "\nWarning: The codepage of the graph window (%i) and that of the\n" \ "console (%i) differ. Use `set encoding` or `!chcp` if extended\n" \ "characters don't display correctly.\n", GetACP(), GetConsoleCP()); } #endif #endif update_gpval_variables(3); /* update GPVAL_ variables available to user */ #ifdef VMS /* initialise screen management routines for command recall */ if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL) done(status[1]); if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL) done(status[1]); #endif /* VMS */ if (!SETJMP(command_line_env, 1)) { /* first time */ interrupt_setup(); /* should move this stuff another initialisation routine, * something like init_set() maybe */ get_user_env(); init_loadpath(); init_locale(); /* HBB: make sure all variables start in the same mode 'reset' * would set them to. Since the axis variables aren't in * initialized arrays any more, this is now necessary... */ reset_command(); init_color(); /* Initialization of color */ load_rcfile(); init_fit(); /* Initialization of fitting module */ if (interactive && term != 0) { /* not unknown */ #ifdef GNUPLOT_HISTORY FPRINTF((stderr, "Before read_history\n")); #if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE) expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE); #else expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE); gp_expand_tilde(&expanded_history_filename); #endif FPRINTF((stderr, "expanded_history_filename = %s\n", expanded_history_filename)); read_history(expanded_history_filename); { /* BEGIN: Go local to get environment variable */ const char *temp_env = getenv ("GNUPLOT_HISTORY_SIZE"); if (temp_env) gnuplot_history_size = strtol (temp_env, (char **) NULL, 10); } /* END: Go local to get environment variable */ /* * It is safe to ignore the return values of 'atexit()' and * 'on_exit()'. In the worst case, there is no history of your * currrent session and you have to type all again in your next * session. * This is the default behaviour (traditional reasons), too. * In case you don't have one of these functions, or you don't * want to use them, 'write_history()' is called directly. */ GP_ATEXIT(wrapper_for_write_history); #endif /* GNUPLOT_HISTORY */ fprintf(stderr, "\nTerminal type set to '%s'\n", term->name); } /* if (interactive && term != 0) */ } else { /* come back here from int_error() */ if (interactive == FALSE) exit_status = EXIT_FAILURE; #ifdef HAVE_READLINE_RESET else { /* reset properly readline after a SIGINT+longjmp */ rl_reset_after_signal (); } #endif load_file_error(); /* if we were in load_file(), cleanup */ SET_CURSOR_ARROW; #ifdef VMS /* after catching interrupt */ /* VAX stuffs up stdout on SIGINT while writing to stdout, so reopen stdout. */ if (gpoutfile == stdout) { if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) { /* couldn't reopen it so try opening it instead */ if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) { /* don't use int_error here - causes infinite loop! */ fputs("Error opening SYS$OUTPUT as stdout\n", stderr); } } gpoutfile = stdout; } #endif /* VMS */ if (!interactive && !noinputfiles) { term_reset(); exit(EXIT_FAILURE); /* exit on non-interactive error */ } } if (argc > 1) { #ifdef _Windows TBOOLEAN noend = persist_cl; #endif /* load filenames given as arguments */ while (--argc > 0) { ++argv; c_token = 0; #ifdef _Windows if (stricmp(*argv, "-noend") == 0 || stricmp(*argv, "/noend") == 0 || stricmp(*argv, "-persist") == 0) noend = TRUE; else #endif if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")) { FPRINTF((stderr,"'persist' command line option recognized\n")); } else if (strcmp(*argv, "-") == 0) { interactive = TRUE; while (!com_line()); interactive = FALSE; } else if (strcmp(*argv, "-e") == 0) { --argc; ++argv; if (argc <= 0) { fprintf(stderr, "syntax: gnuplot -e \"commands\"\n"); return 0; } do_string(*argv); } else { load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), FALSE); } } #ifdef _Windows if (noend) { interactive = TRUE; while (!com_line()); } #endif } else { /* take commands from stdin */ while (!com_line()); } #if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY) #if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT) /* You should be here if you neither have 'atexit()' nor 'on_exit()' */ wrapper_for_write_history(); #endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */ #endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */ #ifdef OS2 RexxDeregisterSubcom("GNUPLOT", NULL); #endif /* HBB 20040223: Not all compilers like exit() to end main() */ /* exit(exit_status); */ return exit_status; }
/** * cairo_os2_surface_create: * @hps_client_window: the presentation handle to bind the surface to * @width: the width of the surface * @height: the height of the surface * * Create a Cairo surface which is bound to a given presentation space (HPS). * The surface will be created to have the given size. * By default every change to the surface will be made visible immediately by * blitting it into the window. This can be changed with * cairo_os2_surface_set_manual_window_refresh(). * Note that the surface will contain garbage when created, so the pixels have * to be initialized by hand first. You can use the Cairo functions to fill it * with black, or use cairo_surface_mark_dirty() to fill the surface with pixels * from the window/HPS. * * Return value: the newly created surface * * Since: 1.4 **/ cairo_surface_t * cairo_os2_surface_create (HPS hps_client_window, int width, int height) { cairo_os2_surface_t *local_os2_surface; cairo_status_t status; int rc; /* Check the size of the window */ if ((width <= 0) || (height <= 0)) { /* Invalid window size! */ return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_INVALID_SIZE)); } local_os2_surface = (cairo_os2_surface_t *) malloc (sizeof (cairo_os2_surface_t)); if (!local_os2_surface) { /* Not enough memory! */ return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY)); } /* Initialize the OS/2 specific parts of the surface! */ /* Create mutex semaphore */ rc = DosCreateMutexSem (NULL, &(local_os2_surface->hmtx_use_private_fields), 0, FALSE); if (rc != NO_ERROR) { /* Could not create mutex semaphore! */ free (local_os2_surface); return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY)); } /* Save PS handle */ local_os2_surface->hps_client_window = hps_client_window; /* Defaults */ local_os2_surface->hwnd_client_window = NULLHANDLE; local_os2_surface->blit_as_changes = TRUE; local_os2_surface->pixel_array_lend_count = 0; rc = DosCreateEventSem (NULL, &(local_os2_surface->hev_pixel_array_came_back), 0, FALSE); if (rc != NO_ERROR) { /* Could not create event semaphore! */ DosCloseMutexSem (local_os2_surface->hmtx_use_private_fields); free (local_os2_surface); return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY)); } /* Prepare BITMAPINFO2 structure for our buffer */ memset (&(local_os2_surface->bitmap_info), 0, sizeof (local_os2_surface->bitmap_info)); local_os2_surface->bitmap_info.cbFix = sizeof (BITMAPINFOHEADER2); local_os2_surface->bitmap_info.cx = width; local_os2_surface->bitmap_info.cy = height; local_os2_surface->bitmap_info.cPlanes = 1; local_os2_surface->bitmap_info.cBitCount = 32; /* Allocate memory for pixels */ local_os2_surface->pixels = (unsigned char *) _buffer_alloc (height, width, 4); if (!(local_os2_surface->pixels)) { /* Not enough memory for the pixels! */ DosCloseEventSem (local_os2_surface->hev_pixel_array_came_back); DosCloseMutexSem (local_os2_surface->hmtx_use_private_fields); free (local_os2_surface); return _cairo_surface_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY)); } /* Create image surface from pixel array */ local_os2_surface->image_surface = (cairo_image_surface_t *) cairo_image_surface_create_for_data (local_os2_surface->pixels, CAIRO_FORMAT_ARGB32, width, /* Width */ height, /* Height */ width * 4); /* Rowstride */ status = local_os2_surface->image_surface->base.status; if (status) { /* Could not create image surface! */ _buffer_free (local_os2_surface->pixels); DosCloseEventSem (local_os2_surface->hev_pixel_array_came_back); DosCloseMutexSem (local_os2_surface->hmtx_use_private_fields); free (local_os2_surface); return _cairo_surface_create_in_error (status); } /* Initialize base surface */ _cairo_surface_init (&local_os2_surface->base, &cairo_os2_surface_backend, _cairo_content_from_format (CAIRO_FORMAT_ARGB32)); return (cairo_surface_t *)local_os2_surface; }
int os2ClientSelect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) { static BOOL FirstTime=TRUE; static haveTCPIP=TRUE; ULONG timeout_ms; ULONG postCount, start_millis,now_millis; char faildata[16]; struct select_data sd; BOOL any_ready; int np,ns, i,ready_handles,n; APIRET rc; sd.have_read=FALSE; sd.have_write=FALSE; sd.socket_nread=0; sd.socket_nwrite=0; sd.socket_ntotal=0; sd.max_fds=31; ready_handles=0; any_ready=FALSE; sd.pipe_ntotal=0; sd.pipe_have_write=FALSE; if(FirstTime){ /* First load the so32dll.dll module and get a pointer to the SELECT fn */ if((rc=DosLoadModule(faildata,sizeof(faildata),"SO32DLL",&hmod_so32dll))!=0){ fprintf(stderr, "Could not load module so32dll.dll, rc = %d. Error note %s\n",rc,faildata); haveTCPIP=FALSE; } if((rc = DosQueryProcAddr(hmod_so32dll, 0, "SELECT", (PPFN)&os2_tcp_select))!=0){ fprintf(stderr, "Could not query address of SELECT, rc = %d.\n",rc); haveTCPIP=FALSE; } /* Call these a first time to set the semaphore */ rc = DosCreateEventSem(NULL, &hPipeSem, DC_SEM_SHARED, FALSE); if(rc) { fprintf(stderr, "Could not create event semaphore, rc=%d\n",rc); return(-1); } rc = DosResetEventSem(hPipeSem, &postCount); FirstTime = FALSE; } /* Set up the time delay structs */ if(timeout!=NULL) { timeout_ms=timeout->tv_sec*1000+timeout->tv_usec/1000; } else { timeout_ms=1000000; } /* This should be large enough... */ if(timeout_ms>0) start_millis=os2_get_sys_millis(); /* Copy the masks */ {FD_ZERO(&sd.read_copy);} {FD_ZERO(&sd.write_copy);} if(readfds!=NULL){ XFD_COPYSET(readfds,&sd.read_copy); sd.have_read=TRUE;} if(writefds!=NULL) {XFD_COPYSET(writefds,&sd.write_copy);sd.have_write=TRUE;} /* And zero the original masks */ if(sd.have_read){ FD_ZERO(readfds);} if(sd.have_write) {FD_ZERO(writefds);} if(exceptfds != NULL) {FD_ZERO(exceptfds);} /* Now we parse the fd_sets passed to select and separate pipe/sockets */ n = os2_parse_select(&sd,nfds); if(n == -1) { errno = EBADF; return (-1); } /* Now we have three cases: either we have sockets, pipes, or both */ /* We handle all three cases differently to optimize things */ /* Case 1: only pipes! */ if((sd.pipe_ntotal >0) && (!sd.socket_ntotal)){ np = os2_check_pipes(&sd,readfds,writefds); if(np > 0){ return (np); } else if (np == -1) { return(-1); } while(!any_ready){ rc = DosWaitEventSem(hPipeSem, timeout_ms); if(rc == 640) { return(0); } if((rc != 0) && (rc != 95)) {errno= EBADF; return(-1);} np = os2_check_pipes(&sd,readfds,writefds); if (np > 0){ return(np); } else if (np < 0){ return(-1); } } } /* Case 2: only sockets. Just let the os/2 tcp select do the work */ if((sd.socket_ntotal > 0) && (!sd.pipe_ntotal)){ ns = os2_check_sockets(&sd, readfds, writefds, timeout_ms); return (ns); } /* Case 3: combination of both */ if((sd.socket_ntotal > 0) && (sd.pipe_ntotal)){ np = os2_check_pipes(&sd,readfds,writefds); if(np > 0){ any_ready=TRUE; ready_handles += np; } else if (np == -1) { return(-1); } ns = os2_check_sockets(&sd,readfds,writefds, 0); if(ns>0){ ready_handles+=ns; any_ready = TRUE; } else if (ns == -1) {return(-1);} while (!any_ready && timeout_ms){ rc = DosWaitEventSem(hPipeSem, 10L); if(rc == 0){ np = os2_check_pipes(&sd,readfds,writefds); if(np > 0){ ready_handles+=np; any_ready = TRUE; } else if (np == -1) { return(-1); } } ns = os2_check_sockets(&sd,readfds,writefds,exceptfds, 0); if(ns>0){ ready_handles+=ns; any_ready = TRUE; } else if (ns == -1) {return(-1);} if (i%8 == 0) { now_millis = os2_get_sys_millis(); if((now_millis-start_millis) > timeout_ms) timeout_ms = 0; } i++; } } return(ready_handles); }
/* * Close device. */ void scsi_close_device ( ) { if (scsi_fd != -1) close(scsi_fd); scsi_fd = -1; } //----------------------------------------------------------------------------- #else /* OS/2 */ int scsi_open_device (void) { ULONG rc; // return value ULONG ActionTaken; // return value USHORT openSemaReturn; // return value USHORT lockSegmentReturn; // return value unsigned long cbreturn; unsigned long cbParam; if (!scsi_device) { /* Return if no SCSI device is specified */ fprintf(stderr, "scsi_open_device: no device specified\n"); return(RET_FAIL); } scsi_id = atoi(scsi_device); if (scsi_id < 0 || scsi_id > 15) { fprintf(stderr, "scsi_open_device: bad SCSI ID %s\n", scsi_device); return (RET_FAIL); } /* endif */ // Allocate data buffer. rc = DosAllocMem(&buffer, SCSI_BUFSIZE, OBJ_TILE | PAG_READ | PAG_WRITE | PAG_COMMIT); if (rc) { fprintf(stderr, "scsi_open_device: can't allocate memory\n"); return (RET_FAIL); } rc = DosOpen((PSZ) "aspirou$", // open driver &driver_handle, &ActionTaken, 0, 0, FILE_OPEN, OPEN_SHARE_DENYREADWRITE | OPEN_ACCESS_READWRITE, NULL); if (rc) { // opening failed -> return false fprintf(stderr, "scsi_open_device: opening failed.\n"); return (RET_FAIL); } rc = DosCreateEventSem(NULL, &postSema, // create event semaphore DC_SEM_SHARED, 0); if (rc) { // DosCreateEventSem failed fprintf(stderr, "scsi_open_device: couldn't create semaphore.\n"); return (RET_FAIL); } rc = DosDevIOCtl(driver_handle, 0x92, 0x03, // pass semaphore handle (void*) &postSema, sizeof(HEV), // to driver &cbParam, (void*) &openSemaReturn, sizeof(USHORT), &cbreturn); if (rc || openSemaReturn) { fprintf(stderr, "scsi_open_device: couldn't set semaphore.\n"); return (RET_FAIL); } /* endif */ // Lock buffer. rc = DosDevIOCtl(driver_handle, 0x92, 0x04, // pass buffer pointer (void*) buffer, sizeof(PVOID), // to driver &cbParam, (void*) &lockSegmentReturn, sizeof(USHORT), &cbreturn); if (rc || lockSegmentReturn) { // DosDevIOCtl failed fprintf(stderr, "scsi_open_device: Can't lock buffer.\n"); return (RET_FAIL); } return (1); }
int main(VOID) { HEV hevEvent1 = 0; /* Event semaphore handle */ HTIMER htimerEvent1 = 0; /* Timer handle */ APIRET rc = NO_ERROR; /* Return code */ ULONG ulPostCount = 0; /* Semaphore post count */ ULONG i = 0; /* A loop index */ rc = DosCreateEventSem(NULL, /* Unnamed semaphore */ &hevEvent1, /* Handle of semaphore returned */ DC_SEM_SHARED, /* Indicate a shared semaphore */ FALSE); /* Put in RESET state */ if (rc != NO_ERROR) { printf("DosCreateEventSem error: return code = %u\n", rc); return 1; } rc = DosStartTimer(2000L, /* 2 second interval */ (HSEM) hevEvent1, /* Semaphore to post */ &htimerEvent1); /* Timer handler (returned) */ if (rc != NO_ERROR) { printf("DosStartTimer error: return code = %u\n", rc); return 1; } for (i = 1 ; i < 6 ; i++) { rc = DosWaitEventSem(hevEvent1,15000L); /* Wait 15 seconds for timer */ if (rc != NO_ERROR) { printf("DosWaitEventSem error: return code = %u\n", rc); return 1; } rc = DosResetEventSem(hevEvent1, /* Reset the semaphore */ &ulPostCount); /* And get count (should be 1) */ if (rc != NO_ERROR) { printf("DosWaitEventSem error: return code = %u\n", rc); return 1; } printf("Iteration %u: ulPostCount = %u\n", i, ulPostCount); } /* for loop */ rc = DosStopTimer(htimerEvent1); /* Stop the timer */ if (rc != NO_ERROR) { printf("DosCloseEventSem error: return code = %u\n", rc); return 1; } rc = DosCloseEventSem(hevEvent1); /* Get rid of semaphore */ if (rc != NO_ERROR) { printf("DosCloseEventSem error: return code = %u\n", rc); return 1; } return NO_ERROR; }
int main(VOID) { HMUX hmuxHandAny = NULLHANDLE; /* Muxwaithandle */ HEV hev[5] = {0}; /* Event semaphores */ SEMRECORD apsr[5] = {{0}}; /* Semaphore records */ APIRET rc = NO_ERROR; /* Return code */ ULONG ulLoop = 0; /* Loop count */ ULONG ulSem = 0; for (ulLoop = 0; ulLoop < 5; ulLoop++) { rc = DosCreateEventSem((PSZ) NULL, &hev[ulLoop], 0, FALSE); if (rc != NO_ERROR) { printf("DosCreateEventSem error: return code = %u\n", rc); return 1; } apsr[ulLoop].hsemCur = (HSEM) hev[ulLoop], apsr[ulLoop].ulUser = 0; } /* endfor */ rc = DosCreateMuxWaitSem((PSZ) NULL, &hmuxHandAny, 5L, /* Number of semaphores in list */ apsr, /* Semaphore list */ DCMW_WAIT_ANY); /* Wait for any semaphore */ if (rc != NO_ERROR) { printf("DosCreateMuxWaitSem error: return code = %u\n", rc); return 1; } rc = DosWaitMuxWaitSem(hmuxHandAny, SEM_IMMEDIATE_RETURN, &ulSem); /* No semaphores have been posted, so we should see a timeout below... */ if (rc != ERROR_TIMEOUT) { printf("DosWaitMuxWaitSem error: return code = %u\n", rc); return 1; } rc = DosDeleteMuxWaitSem(hmuxHandAny, apsr[0].hsemCur); if (rc != NO_ERROR) { printf("DosDeleteMuxWaitSem error: return code = %u\n", rc); return 1; } rc = DosCloseMuxWaitSem(hmuxHandAny); if (rc != NO_ERROR) { printf("DosCloseMuxWaitSem error: return code = %u\n", rc); return 1; } return NO_ERROR; }
static grPMSurface* init_surface( grPMSurface* surface, grBitmap* bitmap ) { PBITMAPINFO2 bit; SIZEL sizl = { 0, 0 }; LONG palette[256]; LOG(( "Os2PM: init_surface( %08lx, %08lx )\n", (long)surface, (long)bitmap )); LOG(( " -- input bitmap =\n" )); LOG(( " -- mode = %d\n", bitmap->mode )); LOG(( " -- grays = %d\n", bitmap->grays )); LOG(( " -- width = %d\n", bitmap->width )); LOG(( " -- height = %d\n", bitmap->rows )); /* create the bitmap - under OS/2, we support all modes as PM */ /* handles all conversions automatically.. */ if ( grNewBitmap( bitmap->mode, bitmap->grays, bitmap->width, bitmap->rows, bitmap ) ) return 0; LOG(( " -- output bitmap =\n" )); LOG(( " -- mode = %d\n", bitmap->mode )); LOG(( " -- grays = %d\n", bitmap->grays )); LOG(( " -- width = %d\n", bitmap->width )); LOG(( " -- height = %d\n", bitmap->rows )); bitmap->pitch = -bitmap->pitch; surface->root.bitmap = *bitmap; /* create the image and event lock */ DosCreateEventSem( NULL, &surface->event_lock, 0, TRUE ); DosCreateMutexSem( NULL, &surface->image_lock, 0, FALSE ); /* create the image's presentation space */ surface->image_dc = DevOpenDC( gr_anchor, OD_MEMORY, (PSZ)"*", 0L, 0L, 0L ); surface->image_ps = GpiCreatePS( gr_anchor, surface->image_dc, &sizl, PU_PELS | GPIT_MICRO | GPIA_ASSOC | GPIF_DEFAULT ); GpiSetBackMix( surface->image_ps, BM_OVERPAINT ); /* create the image's PM bitmap */ bit = (PBITMAPINFO2)grAlloc( sizeof(BITMAPINFO2) + 256*sizeof(RGB2) ); surface->bitmap_header = bit; bit->cbFix = sizeof( BITMAPINFOHEADER2 ); bit->cx = surface->root.bitmap.width; bit->cy = surface->root.bitmap.rows; bit->cPlanes = 1; bit->argbColor[0].bBlue = 255; bit->argbColor[0].bGreen = 0; bit->argbColor[0].bRed = 0; bit->argbColor[1].bBlue = 0; bit->argbColor[1].bGreen = 255; bit->argbColor[1].bRed = 0; bit->cBitCount = (bitmap->mode == gr_pixel_mode_gray ? 8 : 1 ); if (bitmap->mode == gr_pixel_mode_gray) { RGB2* color = bit->argbColor; int x, count; count = bitmap->grays; for ( x = 0; x < count; x++, color++ ) { color->bBlue = color->bGreen = color->bRed = (((count-x)*255)/count); } } else { RGB2* color = bit->argbColor; color[0].bBlue = color[0].bGreen = color[0].bRed = 0; color[1].bBlue = color[1].bGreen = color[1].bRed = 255; } surface->os2_bitmap = GpiCreateBitmap( surface->image_ps, (PBITMAPINFOHEADER2)bit, 0L, NULL, NULL ); GpiSetBitmap( surface->image_ps, surface->os2_bitmap ); bit->cbFix = sizeof( BITMAPINFOHEADER2 ); GpiQueryBitmapInfoHeader( surface->os2_bitmap, (PBITMAPINFOHEADER2)bit ); surface->bitmap_header = bit; /* for gr_pixel_mode_gray, create a gray-levels logical palette */ if ( bitmap->mode == gr_pixel_mode_gray ) { int x, count; count = bitmap->grays; for ( x = 0; x < count; x++ ) palette[x] = (((count-x)*255)/count) * 0x010101; /* create logical color table */ GpiCreateLogColorTable( surface->image_ps, (ULONG) LCOL_PURECOLOR, (LONG) LCOLF_CONSECRGB, (LONG) 0L, (LONG) count, (PLONG) palette ); /* now, copy the color indexes to surface->shades */ for ( x = 0; x < count; x++ ) surface->shades[x] = GpiQueryColorIndex( surface->image_ps, 0, palette[x] ); } /* set up the blit points array */ surface->blit_points[1].x = surface->root.bitmap.width; surface->blit_points[1].y = surface->root.bitmap.rows; surface->blit_points[3] = surface->blit_points[1]; /* Finally, create the event handling thread for the surface's window */ DosCreateThread( &surface->message_thread, (PFNTHREAD) RunPMWindow, (ULONG) surface, 0UL, 32920 ); /* wait for the window creation */ LOCK(surface->image_lock); UNLOCK(surface->image_lock); surface->root.done = (grDoneSurfaceFunc) done_surface; surface->root.refresh_rect = (grRefreshRectFunc) refresh_rectangle; surface->root.set_title = (grSetTitleFunc) set_title; surface->root.listen_event = (grListenEventFunc) listen_event; /* convert_rectangle( surface, 0, 0, bitmap->width, bitmap->rows ); */ return surface; }