コード例 #1
0
ファイル: asteroids.cpp プロジェクト: jacobfrench/CS335-Labs
int main(void)
{
	logOpen();
	initXWindows();
	init_opengl();
	Game game;
	init(&game);
	srand(time(NULL));
	clock_gettime(CLOCK_REALTIME, &timePause);
	clock_gettime(CLOCK_REALTIME, &timeStart);
	int done=0;
	while (!done) {
		while (XPending(dpy)) {
			XEvent e;
			XNextEvent(dpy, &e);
			check_resize(&e);
			check_mouse(&e);
			done = check_keys(&e);
		}
		clock_gettime(CLOCK_REALTIME, &timeCurrent);
		timeSpan = timeDiff(&timeStart, &timeCurrent);
		timeCopy(&timeStart, &timeCurrent);
		physicsCountdown += timeSpan;
		while (physicsCountdown >= physicsRate) {
			physics(&game);
			physicsCountdown -= physicsRate;
		}
		render(&game);
		glXSwapBuffers(dpy, win);
	}
	cleanupXWindows();
	cleanup_fonts();
	logClose();
	return 0;
}
コード例 #2
0
void
ServerFree(TServer * const serverP) {

    struct _TServer * const srvP = serverP->srvP;

    if (srvP->weCreatedListenSocket)
        SocketDestroy(srvP->listenSocketP);

    xmlrpc_strfree(srvP->name);

    xmlrpc_strfree(srvP->filespath);
    
    ListFree(&srvP->defaultfilenames);

    terminateHandlers(&srvP->handlers);

    ListFree(&srvP->handlers);

    logClose(srvP);

    if (srvP->logfilename)
        xmlrpc_strfree(srvP->logfilename);

    free(srvP);
}
コード例 #3
0
ファイル: _sqlFreeEnv.c プロジェクト: ppslinux/unixODBC
SQLRETURN sqlFreeEnv( SQLHENV hDrvEnv )
{
    HDRVENV hEnv	= (HDRVENV)hDrvEnv;

    /* SANITY CHECKS */
    if( hEnv == SQL_NULL_HENV )
        return SQL_INVALID_HANDLE;

    sprintf( hEnv->szSqlMsg, "hEnv = $%08lX", hEnv );
    logPushMsg( hEnv->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, hEnv->szSqlMsg );

    if ( hEnv->hFirstDbc != NULL )
    {
        logPushMsg( hEnv->hLog, __FILE__, __FILE__, __LINE__, LOG_WARNING, LOG_WARNING, "SQL_ERROR There are allocated Connections" );
        return SQL_ERROR;
    }

    /************
     * 	!!! ADD CODE TO FREE DRIVER SPECIFIC MEMORY (hidden in hEnvExtras) HERE !!!
     ************/
    free( hEnv->hEnvExtras );
    logPushMsg( hEnv->hLog, __FILE__, __FILE__, __LINE__, LOG_INFO, LOG_INFO, "SQL_SUCCESS" );
    logClose( hEnv->hLog );
    free( hEnv );

    return SQL_SUCCESS;
}
コード例 #4
0
ファイル: log.c プロジェクト: ErikOnBike/light-play
bool logSetFileInternal(FILE *newLogFile) {
	/* Close any open log-file. */
	if(!logClose()) {
		return false;
	}
	logFile = newLogFile;
	return true;
}
コード例 #5
0
ファイル: BehavePlus5.cpp プロジェクト: cbevins/BehavePlus5
static void stopLog( void )
{
    time_t now = time((time_t *) NULL);
    log( "\n" );
    log( QString( Program + " " + Version + " stopped on " + ctime(&now) ),
        true );
    logClose();
    return;
}
コード例 #6
0
ファイル: FUSE_operations.c プロジェクト: kair/mds_scaling
void GIGAdestroy(void * unused)
{
    (void)unused;

    logClose();

    /* FIXME: check cleanup code.
    rpc_disconnect();
    */
}
コード例 #7
0
ファイル: rainforest.c プロジェクト: DrewLane24/Project
int main(void)
{
	logOpen();
	initXWindows();
	init_opengl();
	init();
	init_sounds();
	clock_gettime(CLOCK_REALTIME, &timePause);
	clock_gettime(CLOCK_REALTIME, &timeStart);
	while(!done) {
		while(XPending(dpy)) {
			XEvent e;
			XNextEvent(dpy, &e);
			check_resize(&e);
			check_mouse(&e);
			check_keys(&e);
		}
		//
		//Below is a process to apply physics at a consistent rate.
		//1. Get the time right now.
		clock_gettime(CLOCK_REALTIME, &timeCurrent);
		//2. How long since we were here last?
		timeSpan = timeDiff(&timeStart, &timeCurrent);
		//3. Save the current time as our new starting time.
		timeCopy(&timeStart, &timeCurrent);
		//4. Add time-span to our countdown amount.
		physicsCountdown += timeSpan;
		//5. Has countdown gone beyond our physics rate? 
		//       if yes,
		//           In a loop...
		//              Apply physics
		//              Reducing countdown by physics-rate.
		//              Break when countdown < physics-rate.
		//       if no,
		//           Apply no physics this frame.
		while(physicsCountdown >= physicsRate) {
			//6. Apply physics
			physics();
			//7. Reduce the countdown by our physics-rate
			physicsCountdown -= physicsRate;
		}
		//Always render every frame.
		render();
		glXSwapBuffers(dpy, win);
	}
	cleanupXWindows();
	cleanup_fonts();
	#ifdef USE_SOUND
	fmod_cleanup();
	#endif //USE_SOUND
	logClose();
	return 0;
}
コード例 #8
0
ファイル: mlogger.c プロジェクト: Unidata/LDM
static int archiveLog (LOGGER *p_logger, char *archiveDate) {

	int		retval	= SUCCESS;
	char		archivePath[LOG_MAX_PATH_LEN+1];
	char		*fname;
	char		*ext;
	char		timeStr[64];	/* .HH.MM.SS */
	char		newName[LOG_MAX_FILENAME_LEN+1];
	struct tm	*lt;

	if (p_logger == NULL) {
		fprintf (stderr, "ERROR: %s - NULL logger provided\n", __FUNCTION__);
		return ERROR;
	}

	if (!(p_logger->optionMask & NODE_IN_USE)) {
		fprintf (stderr, "ERROR: %s - Logger not in use\n", __FUNCTION__);
		return ERROR;
	}

	sprintf (archivePath, "%s/%s", p_logger->archivePath, archiveDate);
	if (!fileExists (archivePath)) {
		if (makeDirectory (archivePath, YES, DIRECTORY_CREATE_PERMS)) {
			fprintf (stderr, "ERROR: %s - could not create directory %s\n", __FUNCTION__, archivePath);
			retval = ERROR;
		}
	}

	fname = strdup (p_logger->logName);
	splitFilenameExt (fname, &ext);		/* Remove the extension, if there is one */

	lt = localtime (&p_logger->lastLogTime);
	sprintf (timeStr, "%02d.%02d.%02d", lt->tm_hour, lt->tm_min, lt->tm_sec);

	sprintf (newName, "%s/%s.%s", archivePath, fname, timeStr);
	free (fname);

	if (p_logger->optionMask & O_LOG_INIT) {
		p_logger->amArchiving = TRUE;
		logMsg (p_logger, V_ALWAYS, S_STATUS, "%s ARCHIVED TO %s", p_logger->name, newName);
		p_logger->amArchiving = FALSE;
	}

	logClose (p_logger);

	if (moveFile (p_logger->fullLogName, newName, NO)) {
		fprintf (stderr, "ERROR: %s - could not move %s to %s\n", __FUNCTION__, p_logger->fullLogName, archivePath);
		retval = ERROR;
	}

	return retval;
}
コード例 #9
0
ファイル: mlogger.c プロジェクト: Unidata/LDM
int logCloseLogger (LOGGER *pl) {

	if (pl == NULL) {
		fprintf (stderr, "ERROR: %s - NULL logger provided\n", __FUNCTION__);
		return ERROR;
	}

	if (!(pl->optionMask & NODE_IN_USE)) {
		fprintf (stderr, "ERROR: %s - Logger not in use\n", __FUNCTION__);
		return ERROR;
	}

	if (pl->optionMask & O_LOG_INIT) {
		logMsg (pl, V_INFO, S_STATUS, "%s HALTED", pl->name);
	}

	logClose (pl);

	free (pl->archivePath);
	free (pl->buffer);
	free (pl->fullLogName);
	free (pl->logName);
	free (pl->logPath);
	free (pl->timeFormat);
	free (pl->formatBuf);
	free (pl->name);

	pl->logSize		= 0;
	pl->lastLogTime		= 0;
	pl->lastLogDay		= 0;
	pl->rollOverSize	= 0;
	pl->optionMask		= 0;	/* This turns off the IN_USE flag */
	pl->verbosity		= 0;

	loggerStore.count--;
	/* If this is the last logger in the loggerStore array, free it */
	if (pl->index == loggerStore.count) {
		if (loggerStore.count > 0) {
			if ((loggerStore.loggers = (LOGGER **) realloc (loggerStore.loggers, sizeof (LOGGER *) * (loggerStore.count))) == NULL) {
				fprintf (stderr, "ERROR: %s - Could not realloc loggerStore\n", __FUNCTION__);
				return ERROR;
			}
		} else {
			free (loggerStore.loggers);
		}
	}

	free (pl);

	return SUCCESS;
}
コード例 #10
0
void logDisplay()
{
    if(receivingLog) {
        logDump(logFile, &logInfo, logStorage, logTotal);
        logClose();

        if(logTotal > 0)
            consolePrintf("\n");
        
        consoleNotef("LOG DUMP COMPLETED\n");
    }
    
    logTotal = 0;
}
コード例 #11
0
SQLRETURN _FreeStmt( SQLHSTMT hDrvStmt )
{
	#ifndef __FUNC__
		#define _OTAR_RM_FUNC_
		#define __FUNC__ "_FreeStmt"
	#endif
    HDRVSTMT hStmt	= (HDRVSTMT)hDrvStmt;
	HDRVSTMT	hPrevStmt;
	SQLRETURN	nReturn;

	if ( hStmt == SQL_NULL_HDBC )
		return SQL_ERROR;

	/* SPECIAL CHECK FOR FIRST IN LIST 				*/
	if ( ((HDRVDBC)hStmt->hDbc)->hFirstStmt == hStmt )
		((HDRVDBC)hStmt->hDbc)->hFirstStmt = hStmt->pNext;
	
	/* SPECIAL CHECK FOR LAST IN LIST 				*/
	if ( ((HDRVDBC)hStmt->hDbc)->hLastStmt == hStmt )
		((HDRVDBC)hStmt->hDbc)->hLastStmt = hStmt->pPrev;

	/* EXTRACT SELF FROM LIST						*/
	if ( hStmt->pPrev != SQL_NULL_HSTMT )
		hStmt->pPrev->pNext = hStmt->pNext;
	if ( hStmt->pNext != SQL_NULL_HSTMT )
		hStmt->pNext->pPrev = hStmt->pPrev;

	/* FREE STANDARD MEMORY */
	if( NULL != hStmt->pszQuery ) free( hStmt->pszQuery );

/*********************************************************************/
/* 	!!! FREE DRIVER SPECIFIC MEMORY (hidden in hStmtExtras) HERE !!! */
	_FreeResults( hStmt->hStmtExtras );
	free( hStmt->hStmtExtras );
/*********************************************************************/

	logPushMsg( hStmt->hLog, __FILE__, __FUNC__, __LINE__, LOG_INFO, LOG_INFO, "SQL_SUCCESS" );
	logClose( hStmt->hLog );
	free( hStmt );

	return SQL_SUCCESS;
	#ifdef _OTAR_RM_FUNC_
		#undef _OTAR_RM_FUNC_
		#undef __FUNC__
	#endif
}
コード例 #12
0
int main(void)
{
    logOpen();
    initXWindows();
    init_opengl();
    init();
    //buttonsInit();------------------------------------------------------------------
    init_sounds();
    clock_gettime(CLOCK_REALTIME, &timePause);
    clock_gettime(CLOCK_REALTIME, &timeStart);
    while(!done) {
        while(XPending(dpy)) {
            XEvent e;
            XNextEvent(dpy, &e);
            check_resize(&e);
            check_mouse(&e);
            GOcheck_mouse(&e);
            check_keys(&e);

        }
        clock_gettime(CLOCK_REALTIME, &timeCurrent);
        timeSpan = timeDiff(&timeStart, &timeCurrent);
        timeCopy(&timeStart, &timeCurrent);
        physicsCountdown += timeSpan;
        while(physicsCountdown >= physicsRate) {
            physics();
            physicsCountdown -= physicsRate;
        }
        render();
        glXSwapBuffers(dpy, win);
    }
    cleanupXWindows();
    cleanup_fonts();
#ifdef USE_SOUND
    fmod_cleanup();
#endif //USE_SOUND
    logClose();
    return 0;
}
コード例 #13
0
void handle_sigint(int sig)
{
	if (sig == SIGINT) {
		logNotice("Received SIGINT\n\n");
	} else if (sig == SIGTERM) {
		logNotice("Received SIGTERM\n\n");
	} else {
		return;
	}

#ifdef MY_RF24_IRQ_PIN
	detachInterrupt(MY_RF24_IRQ_PIN);
#endif

#if defined(MY_GATEWAY_SERIAL)
	MY_SERIALDEVICE.end();
#endif

	logClose();

	exit(EXIT_SUCCESS);
}
コード例 #14
0
int
main(int argc, char *argv[])
{
    const int SLEEP_TIME = 15;      /* Time to sleep between messages */
    int count = 0;                  /* Number of completed SLEEP_TIME intervals */
    int unslept;                    /* Time remaining in sleep interval */
    struct sigaction sa;

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    sa.sa_handler = sighupHandler;
    if (sigaction(SIGHUP, &sa, NULL) == -1)
        errExit("sigaction");

    if (becomeDaemon(0) == -1)
        errExit("becomeDaemon");

    logOpen(LOG_FILE);
    readConfigFile(CONFIG_FILE);

    unslept = SLEEP_TIME;

    for (;;) {
        unslept = sleep(unslept);       /* Returns > 0 if interrupted */

        if (hupReceived) {              /* If we got SIGHUP... */
            hupReceived = 0;            /* Get ready for next SIGHUP */
            logClose();
            logOpen(LOG_FILE);
            readConfigFile(CONFIG_FILE);
        }

        if (unslept == 0) {             /* On completed interval */
            count++;
            logMessage("Main: %d", count);
            unslept = SLEEP_TIME;       /* Reset interval */
        }
    }
}
コード例 #15
0
ファイル: 7.19.01.c プロジェクト: apktool/Temp
int main(int argc, char* argv[]){
	const int SLEEP_TIME=15;
	int count=0;
	int unslept;

	struct sigaction sa;
	sigemptyset(&sa.sa_mask);
	//sa.sa_flags=SA_RESTART;
	sa.sa_flags=SA_NOCLDSTOP;
	sa.sa_handler=sighupHandler;
	if(sigaction(SIGHUP,&sa,NULL)==-1){
		perror("error sigation");
	}
	if(becomeDaemon(0)==-1){
		perror("error becomeDaemon");
	}

	logOpen(LOG_FILE);
	readConfigFile(CONFIG_FILE);

	unslept=SLEEP_TIME;

	for(;;){
		unslept=sleep(unslept);
		if(hupReceived){
			hupReceived=0;
			logClose();
			logOpen(LOG_FILE);
			readConfigFile(CONFIG_FILE);
		}
		if(unslept==0){
			count++;
			logMessage("Main: %d", count);
			unslept=SLEEP_TIME;	
		}
	}
	return 0;
}
コード例 #16
0
ファイル: server.c プロジェクト: BehnamEmamian/openholdembot
void
ServerFree(TServer * const serverP) {

    struct _TServer * const srvP = serverP->srvP;

    if (srvP->weCreatedChanSwitch)
        ChanSwitchDestroy(srvP->chanSwitchP);

    xmlrpc_strfree(srvP->name);

    terminateHandlers(&srvP->handlers);

    ListFree(&srvP->handlers);

    HandlerDestroy(srvP->builtinHandlerP);
    
    logClose(srvP);

    if (srvP->logfilename)
        xmlrpc_strfree(srvP->logfilename);

    free(srvP);
}
コード例 #17
0
ファイル: mlogger.c プロジェクト: Unidata/LDM
static void checkLogRollover (LOGGER *p_logger) {

	char		archiveDate[LOG_SIZE_ARCHIVE_DATE+1];
	time_t		now;

	if (p_logger == NULL) {
		fprintf (stderr, "ERROR: %s - NULL logger provided\n", __FUNCTION__);
		return;
	}

	if (!(p_logger->optionMask & NODE_IN_USE)) {
		fprintf (stderr, "ERROR: %s - Logger not in use\n", __FUNCTION__);
		return;
	}

	if ((p_logger->lastLogTime == 0) || (p_logger->logSize == 0))
		return;

	if ((p_logger->optionMask & O_ARCHIVE)) {
		now = time (NULL);
		/* Check if date changed since last run or log reached rollover size and archive it if so */
		if (((now / 86400) != p_logger->lastLogDay) ||
		   (p_logger->rollOverSize && (p_logger->logSize >= p_logger->rollOverSize))) {
			strftime (archiveDate, LOG_SIZE_ARCHIVE_DATE+1, "%b%d", localtime (&p_logger->lastLogTime));
			if (archiveLog(p_logger, archiveDate) == 0) {
				p_logger->lastLogDay = p_logger->lastLogTime = 0;
				p_logger->logSize = 0;
			}

			if (p_logger->optionMask & O_KEEP_OPEN) {
				logOpen (p_logger);
			}
		}
	} else {
		if (p_logger->rollOverSize && (p_logger->logSize >= p_logger->rollOverSize)) {
			char	*oldExt = ".old";
			char	*fname = strdup (p_logger->logName);
			char	*newName = malloc (strlen (p_logger->fullLogName) + strlen (oldExt) + 1);	/* Reserve characters for old extension */
			char	*ext;

			splitFilenameExt (fname, &ext);
			sprintf (newName, "%s/%s.%s", p_logger->logPath, fname, oldExt);

			if (p_logger->optionMask & O_LOG_INIT) {
				p_logger->amArchiving = TRUE;
				logMsg (p_logger, V_ALWAYS, S_STATUS, "%s TERMINATED %s FILE SIZE %d RENAMED TO %s",
					p_logger->name, p_logger->fullLogName, p_logger->logSize, newName);
				p_logger->amArchiving = FALSE;
			}

			logClose (p_logger);
			if (moveFile (p_logger->fullLogName, newName, TRUE)) {
				fprintf (stderr, "ERROR: %s - could not move %s to %s\n", __FUNCTION__, p_logger->fullLogName, newName);
			}
			p_logger->lastLogDay = p_logger->lastLogTime = 0;
			p_logger->logSize = 0;

			if (p_logger->optionMask & O_KEEP_OPEN) {
				logOpen (p_logger);
			}

			free (newName);
			free (fname);
		}
	}
}
コード例 #18
0
int main(int argc, char *argv[])
{
	if(argc > 1) {
		if(argv[1] != NULL) {
			beginTesting();
		}
		return 0;
	}

	logOpen();
	initXWindows();
	init_opengl();
	Game game;
	init(&game);
	srand(time(NULL));
	clock_gettime(CLOCK_REALTIME, &timePause);
	clock_gettime(CLOCK_REALTIME, &timeStart);	

	hud = new Hud(xres ,yres);
	if (TEST_Hud){
		hud->testHUDAll();
		return 0;
	}
	//DEFUALT IS LEVEL 1 SELECTED:
	selected_screen = LEFT;    
	level =1;
	//--------------
	is_gameover = false;
	high_score = 0;
	gameStarted = false;
	lastPaddleHit = 'N';//'N' means no paddle hit

	bombBegin = time(NULL);
	bombRandom = random(7);

	beginSmallLeftPaddle = time(NULL);
	smallLeftPaddleTime = 7;
	beginSmallRightPaddle = time(NULL);
	smallRightPaddleTime = 7;
	hud->setAI(false);//DEFAULT: player2 is human	
	ball_saved_X_velocity = 8.0f * cos(30);
	ball_saved_Y_velocity = 8.0f * sin(90);    
	obstacle_saved_Y_velocity = -5.0;

	int min;
	if (xres<yres){
		min=xres;
	}
	else{
		min=yres;
	}
	bomb_radius = ((int)(3*min)/10);

	//MAIN MENU LOOP 
	while(intro != 0) {
		while (XPending(dpy)) {
			XEvent e;
			XNextEvent(dpy, &e);
			check_resize(&e);
			intro = check_keys(&e, &game);
		}
		render(&game);
		glXSwapBuffers(dpy, win);
	}


	//BEGIN MAIN GAME LOOP
	int done=0;
	while (!done) {        
		while (XPending(dpy)) {
			XEvent e;
			XNextEvent(dpy, &e);
			check_resize(&e);
			done = check_keys(&e, &game);
		}
		clock_gettime(CLOCK_REALTIME, &timeCurrent);
		timeSpan = timeDiff(&timeStart, &timeCurrent);
		timeCopy(&timeStart, &timeCurrent);
		physicsCountdown += timeSpan;
		while (physicsCountdown >= physicsRate) {
			physics(&game);
			physicsCountdown -= physicsRate;
		}        
		render(&game);
		glXSwapBuffers(dpy, win);
	}
	cleanupXWindows();
	cleanup_fonts();
	logClose();

	return 0;
}
コード例 #19
0
ファイル: main.c プロジェクト: alan77916/myCrawler
int main(int argc,char *argv[]){
    if(argc<2)
	usage(0);
    char *sourceURL=argv[1];
    clock_t begin, end;
    int i=0;
    char *handleURL;
    int pos;
    UPU *tmp;
    URL_FILE *buf;
    char prefix[10],host[1024],path[4096],filename[4096];


    for(i=0;i<HashSize;i++){
	URLPool[i]=NULL;
	finishPool[i]=NULL;
	failedPool[i]=NULL;
    }
    memset(prefix,0,10);
    memset(host,0,1024);
    memset(path,0,4096);
    memset(filename,0,4096);
    sepURL(sourceURL,prefix,host,path,filename);
    //check/create Folder    
    folderInit(host);
    readRec(sourceURL);
    //init
    if(!logInit(host)){
	printf("log file error\n");
	exit(1);
    }
    pos=hashfn(sourceURL);
    myAdd(&URLPool[pos],sourceURL,strlen(sourceURL));
    //start loop
    begin=clock();
    i=0;
    while(getPoolSize(URLPool)!=0){
	//random get one URL Structure Pointer from URLPool
	handleURL=randGet(URLPool);
	pos=hashfn(handleURL);
	printf("run [%d] %s\n",pos,handleURL);
	memset(prefix,0,10);
	memset(host,0,1024);
	memset(path,0,4096);
	memset(filename,0,4096);
	sepURL(handleURL,prefix,host,path,filename);
	//put the url in finishPool
	tmp=finishPool[pos];
	if(tmp==NULL){
	    myAdd(&finishPool[pos],handleURL,strlen(handleURL));
	}else{
	    while(tmp->next!=NULL){
		tmp=tmp->next;
	    }
	    myAdd(&(tmp->next),handleURL,strlen(handleURL));
	}
	//start run the CURL
	if((buf=runCURL(handleURL))!=NULL){	    
	    //write to File
	    myWrite(host,filename,buf->buffer,buf->buffer_len,i++);
	    getURL(buf->buffer,buf->buffer_len,handleURL,prefix,host,path,filename);
	    printf("%d\n",getPoolSize(URLPool));
	    memset(buf->buffer,0,buf->buffer_len);
	    free(buf->buffer);
	    fflush(logfp);
	}
	else{
	    printf("no content\n");
	}
	free(buf);
    }
    logClose();
    end=clock();
    printf("finally finish: %d 's URL, cost %lf sec\n",getPoolSize(finishPool),(double)( end - begin ) / CLOCKS_PER_SEC);
    myDump(host);
    return 0;
}
コード例 #20
0
void datagramInterpreter(uint8_t t, const uint8_t *data, int size)
{
    switch(t) {
        case DG_HEARTBEAT:
            // Heartbeat
            if(heartbeatReset) {
                memcpy((void*) &heartbeatCount, data, sizeof(heartbeatCount));
                heartbeatTime = time(NULL);
            }
            break;
            
        case DG_CONSOLE:
            // Console output
            consoleWrite(data, size);
            break;
            
        case DG_INITIALIZED:
            initDone = true;
            break;
            
        case DG_READY:
            // Initialization done
            // consoleNotef("ready\n");
            logReady = true;
            break;
            
        case DG_LOGDATA:
            // Log data
            if(size > 0)
                logStore((const uint16_t*) data, size/2);
            else if(receivingLog) {
                logDisplay();
                logClose();
                // Auto clear
                if(!autoClearDone)
                    sendCommand("clear");
                autoClearDone = true;
            }
            break;
            
        case DG_LOGINFO:
            // Log stamp
            memcpy(&logInfo, data, sizeof(logInfo));
            consoleNotef("LOG %d OF MODEL %s\n", logInfo.stamp, logInfo.name);
            receivingLog = logOpen(&logInfo);
            break;
            
        case DG_PARAMS:
            // Param backup
            if(size > 0) {
                memset(modelName, '\0', NAME_LEN);
                memcpy(modelName, (char*) data, size);
                consoleNotef("BACKUP %s START\n", modelName);
                backupOpen(modelName);;
            } else {
                consoleNotef("BACKUP END\n");
                backupClose();
            }
            break;
            
        case DG_SIMLINK:
            // Simulator link control record
            udpClient(data, size);
            break;

        default:
            consoleNotef("FUNNY DATAGRAM TYPE = %d SIZE = %d\n", t, size);
    }
}
コード例 #21
0
ファイル: get.c プロジェクト: cmwshang/pgbackrest
/***********************************************************************************************************************************
Get an archive file from the repository (WAL segment, history file, etc.)
***********************************************************************************************************************************/
int
cmdArchiveGet(void)
{
    FUNCTION_LOG_VOID(logLevelDebug);

    // Set the result assuming the archive file will not be found
    int result = 1;

    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Check the parameters
        const StringList *commandParam = cfgCommandParam();

        if (strLstSize(commandParam) != 2)
        {
            if (strLstSize(commandParam) == 0)
                THROW(ParamRequiredError, "WAL segment to get required");

            if (strLstSize(commandParam) == 1)
                THROW(ParamRequiredError, "path to copy WAL segment required");

            THROW(ParamInvalidError, "extra parameters found");
        }

        // Get the segment name
        String *walSegment = strBase(strLstGet(commandParam, 0));

        // Destination is wherever we were told to move the WAL segment
        const String *walDestination =
            walPath(strLstGet(commandParam, 1), cfgOptionStr(cfgOptPgPath), STR(cfgCommandName(cfgCommand())));

        // Async get can only be performed on WAL segments, history or other files must use synchronous mode
        if (cfgOptionBool(cfgOptArchiveAsync) && walIsSegment(walSegment))
        {
            bool found = false;                                         // Has the WAL segment been found yet?
            bool queueFull = false;                                     // Is the queue half or more full?
            bool forked = false;                                        // Has the async process been forked yet?
            bool confessOnError = false;                                // Should we confess errors?

            // Loop and wait for the WAL segment to be pushed
            Wait *wait = waitNew((TimeMSec)(cfgOptionDbl(cfgOptArchiveTimeout) * MSEC_PER_SEC));

            do
            {
                // Check for errors or missing files.  For archive-get ok indicates that the process succeeded but there is no WAL
                // file to download.
                if (archiveAsyncStatus(archiveModeGet, walSegment, confessOnError))
                {
                    storageRemoveP(
                        storageSpoolWrite(),
                        strNewFmt(STORAGE_SPOOL_ARCHIVE_IN "/%s" STATUS_EXT_OK, strPtr(walSegment)), .errorOnMissing = true);
                    break;
                }

                // Check if the WAL segment is already in the queue
                found = storageExistsNP(storageSpool(), strNewFmt(STORAGE_SPOOL_ARCHIVE_IN "/%s", strPtr(walSegment)));

                // If found then move the WAL segment to the destination directory
                if (found)
                {
                    // Source is the WAL segment in the spool queue
                    StorageFileRead *source = storageNewReadNP(
                        storageSpool(), strNewFmt(STORAGE_SPOOL_ARCHIVE_IN "/%s", strPtr(walSegment)));

                    // A move will be attempted but if the spool queue and the WAL path are on different file systems then a copy
                    // will be performed instead.
                    //
                    // It looks scary that we are disabling syncs and atomicity (in case we need to copy intead of move) but this
                    // is safe because if the system crashes Postgres will not try to reuse a restored WAL segment but will instead
                    // request it again using the restore_command. In the case of a move this hardly matters since path syncs are
                    // cheap but if a copy is required we could save a lot of writes.
                    StorageFileWrite *destination = storageNewWriteP(
                        storageLocalWrite(), walDestination, .noCreatePath = true, .noSyncFile = true, .noSyncPath = true,
                        .noAtomic = true);

                    // Move (or copy if required) the file
                    storageMoveNP(storageSpoolWrite(), source, destination);

                    // Return success
                    result = 0;

                    // Get a list of WAL segments left in the queue
                    StringList *queue = storageListP(
                        storageSpool(), STORAGE_SPOOL_ARCHIVE_IN_STR, .expression = WAL_SEGMENT_REGEXP_STR);

                    if (strLstSize(queue) > 0)
                    {
                        // Get size of the WAL segment
                        uint64_t walSegmentSize = storageInfoNP(storageLocal(), walDestination).size;

                        // Use WAL segment size to estimate queue size and determine if the async process should be launched
                        queueFull = strLstSize(queue) * walSegmentSize > cfgOptionUInt64(cfgOptArchiveGetQueueMax) / 2;
                    }
                }

                // If the WAL segment has not already been found then start the async process to get it.  There's no point in
                // forking the async process off more than once so track that as well.  Use an archive lock to prevent forking if
                // the async process was launched by another process.
                if (!forked && (!found || !queueFull)  &&
                    lockAcquire(cfgOptionStr(cfgOptLockPath), cfgOptionStr(cfgOptStanza), cfgLockType(), 0, false))
                {
                    // Get control info
                    PgControl pgControl = pgControlFromFile(cfgOptionStr(cfgOptPgPath));

                    // Create the queue
                    storagePathCreateNP(storageSpoolWrite(), STORAGE_SPOOL_ARCHIVE_IN_STR);

                    // The async process should not output on the console at all
                    KeyValue *optionReplace = kvNew();

                    kvPut(optionReplace, VARSTR(CFGOPT_LOG_LEVEL_CONSOLE_STR), VARSTRDEF("off"));
                    kvPut(optionReplace, VARSTR(CFGOPT_LOG_LEVEL_STDERR_STR), VARSTRDEF("off"));

                    // Generate command options
                    StringList *commandExec = cfgExecParam(cfgCmdArchiveGetAsync, optionReplace);
                    strLstInsert(commandExec, 0, cfgExe());

                    // Clean the current queue using the list of WAL that we ideally want in the queue.  queueNeed()
                    // will return the list of WAL needed to fill the queue and this will be passed to the async process.
                    const StringList *queue = queueNeed(
                        walSegment, found, cfgOptionUInt64(cfgOptArchiveGetQueueMax), pgControl.walSegmentSize,
                        pgControl.version);

                    for (unsigned int queueIdx = 0; queueIdx < strLstSize(queue); queueIdx++)
                        strLstAdd(commandExec, strLstGet(queue, queueIdx));

                    // Release the lock so the child process can acquire it
                    lockRelease(true);

                    // Fork off the async process
                    if (forkSafe() == 0)
                    {
                        // Disable logging and close log file
                        logClose();

                        // Detach from parent process
                        forkDetach();

                        // Execute the binary.  This statement will not return if it is successful.
                        THROW_ON_SYS_ERROR(
                            execvp(strPtr(cfgExe()), (char ** const)strLstPtr(commandExec)) == -1,
                            ExecuteError, "unable to execute '" CFGCMD_ARCHIVE_GET_ASYNC "'");
                    }

                    // Mark the async process as forked so it doesn't get forked again.  A single run of the async process should be
                    // enough to do the job, running it again won't help anything.
                    forked = true;
                }

                // Exit loop if WAL was found
                if (found)
                    break;

                // Now that the async process has been launched, confess any errors that are found
                confessOnError = true;
            }
            while (waitMore(wait));
        }
        // Else perform synchronous get
        else
        {
コード例 #22
0
ファイル: mlogger.c プロジェクト: Unidata/LDM
LOGGER *logInitLogger (char *name, int facility, int options, int verbosity, char *logPath,
			char *logName, long rollOverSize, long bufferSize) {

	LOGGER 		*pl;
	int		i;
	struct stat	sb;

	if ((logPath == NULL) || (logPath[0] == '\0')) {
		fprintf (stderr, "ERROR: %s - Invalid logPath passed\n", __FUNCTION__);
		return NULL;
	}

	if ((logName == NULL) || (logName[0] == '\0')) {
		fprintf (stderr, "ERROR: %s - Invalid logName passed\n", __FUNCTION__);
		return NULL;
	}

	if ((facility < F_MIN) || (facility > F_MAX)) {
		fprintf (stderr, "ERROR: %s - Unknown facility %d\n", __FUNCTION__, facility);
		return NULL;
	}

	if (facility != F_FILE) {
		fprintf (stderr, "ERROR: %s - The only facility current supported is F_FILE (%d)\n",
			__FUNCTION__, F_FILE);
		return NULL;
	}

	if ((options & O_FLUSH_AFTER_EACH) && (options & O_TIMED_FLUSH)) {
		fprintf (stderr, "ERROR: %s - O_FLUSH_AFTER_EACH and O_TIMED_FLUSH cannot both be set\n",
			__FUNCTION__);
		return NULL;
	}

	verbosity = (verbosity < V_MIN) ? V_MIN : verbosity;
	verbosity = (verbosity > V_MAX) ? V_MAX : verbosity;

	if (loggerStore.count == 0) {
		i = 0;
		if ((loggerStore.loggers = (LOGGER **) malloc (sizeof (LOGGER *))) == NULL) {
			fprintf (stderr, "ERROR: %s - Could not malloc space for loggerStore array\n", __FUNCTION__);
			return NULL;
		}

		if ((loggerStore.loggers[0] = (LOGGER *) malloc (sizeof (LOGGER))) == NULL) {
			fprintf (stderr, "ERROR: %s - Could not malloc space for logger node\n", __FUNCTION__);
			return NULL;
		}
	} else {	/* Try to find an allocated logger that's not being used */
		for (i = 0; i < loggerStore.count; i++) {
			if (!(loggerStore.loggers[i]->optionMask & NODE_IN_USE)) {
				break;
			}
		}

		if (i >= loggerStore.count) {
			if ((loggerStore.loggers = (LOGGER **) realloc (loggerStore.loggers, sizeof (LOGGER *) * (loggerStore.count+1))) == NULL) {
				fprintf (stderr, "ERROR: %s - Could not realloc loggerStore\n", __FUNCTION__);
				return NULL;
			}

			if ((loggerStore.loggers[i] = (LOGGER *) malloc (sizeof (LOGGER))) == NULL) {
				fprintf (stderr, "ERROR: %s - Could not malloc space for logger node\n", __FUNCTION__);
				return NULL;
			}
		}

	}

	pl = loggerStore.loggers[i];
	pl->index = i;

	loggerStore.count++;
	pl->name = strdup (name);
	options |= NODE_IN_USE;
	pl->optionMask		= options;		/* Set the LOG_IN_USE bit and the flags passed in */
	pl->verbosity		= verbosity;
	pl->facility		= facility;		/* Only supports LOG_FILE now...how to implement others? */
	pl->bufferSize		= bufferSize;
	pl->logFd		= NULL;
	pl->needFlush		= FALSE;
	pl->flushInterval	= LOG_DEFAULT_FLUSH_INTERVAL;
	pl->timerSignal		= SIGRTMIN;
	pl->flushBufSize	= 0;
	pl->amArchiving		= FALSE;

//	switch (p_logger->facility) {
//		case F_FILE:
//			retval = logInitFile (p_logger);
//			break;
//
//		case F_DB:
//			retval = logInitDB (p_logger);
//			break;
//
//		case F_SOCKET:
//			retval = logInitSocket (p_logger);
//			break;
//
//		case F_PIPE:
//			retval = logInitPipe (p_logger);
//			break;
//
//		case F_CONSOLE:
//			retval = logInitConsole (p_logger);
//			break;
//
//		case F_PRINTER:
//			retval = logInitPipe (p_logger);
//			break;
//
//		default:	/* Shouldn't ever get here... */
//			fprintf ("ERROR: %s - hit default case\n", __FUNCTION__);
//			break;
//	}

	/* Force rollover size to LOG_MAX_FILE_SIZE if user leaves it set to 0 */
	pl->rollOverSize = rollOverSize ? rollOverSize : LOG_MAX_FILE_SIZE;

	if ((pl->logPath = strdup (logPath)) == NULL) {
		fprintf (stderr, "ERROR: %s - Could not strdup logPath\n", __FUNCTION__);
		return NULL;
	}

	if ((pl->logName = strdup (logName)) == NULL) {
		fprintf (stderr, "ERROR: %s - Could not strdup logName\n", __FUNCTION__);
		return NULL;
	}

	if ((pl->fullLogName = malloc (strlen (logPath) + strlen (logName) + 2)) == NULL) {
		fprintf (stderr, "ERROR: %s - Could not malloc fullLogName\n", __FUNCTION__);
		return NULL;
	}

	sprintf (pl->fullLogName, "%s/%s", logPath, logName);

	/* This is kludged for now, allow it to be specified later */
	if ((pl->archivePath = malloc (strlen (logPath) + strlen ("/ARCHIVE/MmmDd") + 1)) == NULL) {
		fprintf (stderr, "ERROR: %s - Could not malloc archivePath\n", __FUNCTION__);
		return NULL;
	}

	sprintf (pl->archivePath, "%s/ARCHIVE", logPath);

	if ((pl->timeFormat = strdup (LOG_DEFAULT_DATE_FORMAT)) == NULL) {	/* Hand jam this for now. In future make it configurable */
		fprintf (stderr, "ERROR: %s - Could not strdup date format string\n", __FUNCTION__);
		return NULL;
	}

	if ((pl->buffer = malloc (bufferSize)) == NULL) {
		fprintf (stderr, "ERROR: %s - Could not malloc buffer\n", __FUNCTION__);
		return NULL;
	}

	if ((pl->formatBuf = malloc (LOG_FORMAT_BUF_SIZE)) == NULL) {
		fprintf (stderr, "ERROR: %s - Could not malloc format buffer\n", __FUNCTION__);
		return NULL;
	}

	pl->lastLogDay = pl->lastLogTime = 0;

	if (!fileExists (pl->logPath)) {
		if (makeDirectory (pl->logPath, YES, DIRECTORY_CREATE_PERMS) < 0) {
			fprintf (stderr, "ERROR: %s - Could not make directory for logPath\n", __FUNCTION__);
			return NULL;
		}
	}

	/* Cheat to get the device block size by checking on the block size of the logPath directory file */
	pl->flushBufSize = (stat (pl->logPath, &sb) == 0) ? sb.st_blksize : DEFAULT_DISK_BLOCK_SIZE;

	if (fileExists (pl->fullLogName)) {
		pl->lastLogTime = getFileLastMod (pl->fullLogName);
		pl->lastLogDay = pl->lastLogTime / SECONDS_PER_DAY;
		pl->logSize = getFileSize (pl->fullLogName);
		checkLogRollover (pl);		/* Rollover the log if necessary */
	} else {
		pl->lastLogDay = pl->lastLogTime = 0;
		pl->logSize = 0;
	}

	if (options & O_LOG_INIT) {
		logMsg (pl, V_INFO, S_STATUS, "%s INITIALIZED", pl->name);
		if (!(options & O_KEEP_OPEN)) {
			logClose (pl);
		}
	}

	if (options & O_KEEP_OPEN) {
		logOpen (pl);
	}

	return pl;
}
コード例 #23
0
ファイル: zmq_client.cpp プロジェクト: nkzxw/repo
//#define ULONAG unsigned long
int main(int argc, char* argv[])
{
    progname = argv[0];
    int c;
    int case_type = 0;
    int log_level = -1;
    int conn_type = 0;
    int server_index = 0;
    char server[MAX_SERVER][M_SIZE]={"0"};
    int mds_index = 0;
    char mds[MAX_SERVER][M_SIZE]={"0"};
    char pOutFile[M_SIZE]="\0";
    sprintf(target,"%s","/opt/1.txt");
    sprintf(pOutFile,"%s","/opt/zmq");

    while (1) {
	struct option long_options[] = {
	    {"server",  1,  0, 'd'},
	    {"mds",  1,  0, 'm'},
	    {"file",  1,  0, 'f'},
	    //	    {"compare",  1,  0, 'c'},
	    {"output",  1,  0, 'o'},
	    {"case_type",  1,  0, 't'},
	    {"log_level",  1,  0, 't'},
	    { NULL , NULL , NULL , NULL }
	};
	int option_index = 0;
	c = getopt_long(argc, argv, "m:d:f:o:t:l:", long_options, &option_index);
	if (c == -1)
	    break;
	switch (c) {
	    case 'm':
		sprintf(mds[mds_index],"%s",optarg);
		mds_index++;
		break;
	    case 'd':
		sprintf(server[server_index],"%s",optarg);
		server_index++;
		break;
	    case 'f':
		sprintf(target,"%s",optarg);
		break;
	    case 'o':
		sprintf(pOutFile,"%s",optarg);
		break;
	    case 't':
		case_type = atoi(optarg);
		break;
	    case 'l':
		log_level = atoi(optarg);
		break;
	    default:
		printf ("non-option argv: %c,%s",c,optarg);
		usage();
	}
    }
    logInit(pOutFile);
    if(log_level >= 0)
	DebugLogSetLevel(log_level);
    bw_log(APP_LOG_DEBUG, "%-20s\t%-60s\t","process1","process2");
    bw_log(APP_LOG_DEBUG, "%s\t%-20s\t%-10s\t%-10s","AccessMode","AccessMode","Bwfs","nfs");

    void * g_context = zmq_init(1); 
    //class proc_remote pr4={};
    if ((optind < argc) || (server_index < 1)) {
	printf ("not enough args\n");
	usage();
    }
    class proc_remote *mds_pr[10];
    class proc_remote *pr[10];
    for(int i=0;i < mds_index;i++){
	mds_pr[i]= new proc_remote();
	mds_pr[i]->connect(conn_type,mds[i], g_context);
    }
    for(int i=0;i < server_index;i++){
	pr[i]= new proc_remote();
	pr[i]->connect(conn_type,server[i], g_context);
    }
    //pr3.connect(conn_type,server[2], g_context);
    //pr4.connect(conn_type,server[3]);
    //ha_case1(pr1);
    ha_case2(mds_pr[0],pr[0]);
#if 0
    if (case_type & 1) {
	open_case1(pr1);
	open_case2(pr1, pr2);
	open_case2(pr1, pr3);
    }
#endif
    for(int i=0;i < mds_index;i++){
	mds_pr[i]->zclose(conn_type);
    }
    for(int i=0;i < mds_index;i++){
	pr[i]->zclose(conn_type);
    }
    zmq_term(g_context);
    logClose();

    return 0;
}
コード例 #24
0
int main(int argc, char *argv[])
{
//	Set defaults
	zwdevice = "/dev/ttyUSB0";
	logLevel = 4;	//Log all by default
	v_initflag = 0;
	v_probeflag = 0;
	nodeID=0;
	nodeLevel=0;

	while ((option = getopt (argc, argv, "d:l:n:s:pik")) != -1) {
		switch (option) {
		case 'p':
			v_probeflag = 1;
			break;
		case 'i':
			v_initflag = 1;
			break;
		case 'k':
			v_keepalive = 1;
			break;
		case 'd':
			if(optarg != NULL)
				zwdevice = optarg;
			break;
		case 'l':
			if(optarg != NULL)
				logLevel=atoi(optarg);
				if (logLevel < 1)
					logLevel = 1;
				if (logLevel > 5)
					logLevel = 5;
			break;
		case 'n':
			if(optarg != NULL)
				nodeID=atoi(optarg);
			break;
		case 's':
			if(optarg != NULL)
				nodeLevel=atoi(optarg);
			break;
		default:
			printf("\nUsage:\n");
			printf("zwave <options>\n");
			printf("  -d [device]				Device.  Default device: /dev/ttyUSB0\n");
			printf("  -k 					Keep alive.  Polls devices for status every 30 seconds\n");
			printf("  -l [log level]			Set logging level (1-5)\n");
			printf("					     (1-ERROR, 2-WARN, 3-INFO, 4-ALL (Default), 5-CONSOLE)\n");
			printf("  -n [node ID]				Node ID\n");
			printf("  -p  					Probe Z-Wave devices (work in progress)\n");
			printf("  -s [node level]			Set level (0-255)\n");
			exit (0);
			break;
		}

	}

	logInit("//var//log//zwave.log");
	initZWave(zwdevice);

	if (v_initflag)
		initZWNetwork();

  if (nodeID > 1)
    commandBasicSet(nodeID,nodeLevel, 0);

	if (v_initflag)
		sleep(20);

	if (v_keepalive)
		while(1);

	while (zwQueueIndex > 0)
		usleep(500000);

	logClose();
	return 0;
}