Beispiel #1
0
static void sig_segv_handler(int sig, siginfo_t *info, void *secret) {
	ucontext_t *uc = (ucontext_t *)secret;
	int fd, trace_size = 0;
	void *trace[100];
	struct sigaction sa;
	NOT_USED(info);

	xcb_log(XCB_LOG_WARNING, "\n\n=== XCUBE BUG REPORT START: Cut & paste starting from here ===\n"
		"    xcb-dp2 crashed by signal: %d\n--- STACK TRACE", sig);
	close_logger();
	if ((fd = open("/var/log/xcb/xcb-dp2.log", O_APPEND | O_CREAT | O_WRONLY, 0644)) == -1)
		return;
	trace_size = backtrace(trace, 100);
#ifdef __x86_64__
	trace[1] = (void *)uc->uc_mcontext.gregs[16];
#endif
	backtrace_symbols_fd(trace, trace_size, fd);
	write(fd, "\n=== XCUBE BUG REPORT END. Make sure to include from START to END. ===\n\n", 72);
	close(fd);
	sigemptyset(&sa.sa_mask);
	sa.sa_flags   = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
	sa.sa_handler = SIG_DFL;
	sigaction(sig, &sa, NULL);
	kill(getpid(), sig);
}
Beispiel #2
0
/* FIXME */
static int prepare_for_shutdown(void) {
	xcb_log(XCB_LOG_WARNING, "User requested shutdown...");
	if (udpsock != -1)
		close(udpsock);
	if (tcpsock != -1)
		close(tcpsock);
	xcb_log(XCB_LOG_WARNING, "xcb-dp2 is now ready to exit, bye bye...");
	close_logger();
	return 0;
}
Beispiel #3
0
int
main(int argc, char **argv)
{
    int ret;
    ret = init_logger("./logtest", 0);
    if (ret) {
        printf("log initialization failed\n");
        return -1;
    }
    pthread_t tid;
    printf("creating child threads\n");
    pthread_create(&tid, NULL, logmsg, (void *)0);
    pthread_create(&tid, NULL, logmsg, (void *)1);
    pthread_create(&tid, NULL, logmsg, (void *)2);
    sleep(10);
    close_logger(3);
    
}
Beispiel #4
0
/** Cleanup and destroy the Server */
static inline void cleanup(wr_svr_t *server) {
  LOG_FUNCTION

  // Delete 'webroar.sock' file
  remove(WR_TMP_SOCK_FILE);

  // Stop event loop
  ev_unloop(server->ebb_svr.loop, EVUNLOOP_ALL);

  // Destroy the Server structure
  wr_svr_free(server);

  // Delete 'webroar.pid' file
  remove(WR_PID_FILE);
  LOG_INFO("Shutting down network server. No more request can be served");

  // Destroy logger object
  close_logger();
}
Beispiel #5
0
Datei: lcs.c Projekt: morysky/lcs
int main(int argc, char *argv[]) {
    Logger* general_logger = malloc(sizeof(Logger));
    init_logger(general_logger, LOG_TYPE_FILE, "test.log");
    general_logger->warning(general_logger, "start", "");
    close_logger(general_logger);

    int ret = -1;
    // read conf
    // todo

    /* read opt */
    //todo

    init();

    int myerrno = 0;
    char* errmsg = (char *)malloc(1024);
    memset(errmsg, 0, 1024);
    
    create_server("8989", &myerrno, errmsg);
    return EXIT_SUCCESS;
}
Beispiel #6
0
void stagealign(int fcnum, int lane_num, int initialize)
{

    short unsigned int *testimage;
    short unsigned int *baseimage;
    FILE *baseimgfp;
    FILE *offsetfp;
    /* used to dump score matrix to file when debugging */
    FILE *score_matrixfp;

    /* Maestro declarations */
    int m_sock; /* socket for the Maestro controller */

    char config_value[255];
    char logfilename[255];
    char offsetfilename[255];
    char stagealign_baseimgfilename[255];

    char acqcfgpath[255];

    /* Used to send commands and receive responses from Maestro */
    char command[255];
    char response[255];
    int response_length;

    /* Image acquisition settings, populated from config file */
    int stagealign_integration_inmsec;
    int stagealign_gain;
    int stagealign_well;
    int stagealign_wells_per_fc;

    /* Values used for conversion between pixels and stage units */
    int stagealign_optical_mag;
    int ccd_pixel_size;
    double pixelsize_at_stage; /* size of a pixel at the stage in microns */

    /* Hold offsets found by alignment in pixels and stageunits */
    int pixel_offset_x, pixel_offset_y;
    double stageunit_offset_x, stageunit_offset_y;
    int lane_index;

    /* Holds previous offsets from controller in case the alignment doesn't work */
    int curr_offset_x, curr_offset_y;

    /* Holds encoder resolutions from controller, used for calculating distance of move */
    double encoder_res_X, encoder_res_Y;


    /* 'score' of best alignment */
    int score;

    /* Largest pixel offset allowable _after_ the adjustment has been made */
    /* if there is still a shift larger than this, conclude something is wrong */
    /* and go back to the previous offset */
    int successful_move_threshold = 150; /*RCT was = 12*/

    int i;

  /* in debugging mode, dump internal data to files */
#ifdef DEBUG_STAGEALIGN
    FILE *imgfp;
    sprintf(command, "%s/stagealign-image%d_%d.raw", output_directory, fcnum, lane_num);
    imgfp = fopen(command, "w");
    sprintf(command, "%s/stagealign-scorematrix%d_%d", output_directory, fcnum, lane_num);
    score_matrixfp = fopen(command, "w");
#endif
    p_log_simple("awesome2\n");
    /* Open config file */
    strcpy(acqcfgpath, getenv("POLONATOR_PATH"));
    strcat(acqcfgpath, "/config_files/polonator-acq.cfg");
    config_open(acqcfgpath);
    p_log_simple("awesome1\n");
    /* Initialize variables */
    if(!config_getvalue("stagealign_logfilename", config_value)){
        fprintf(stderr, "ERROR:\tPolonator-stagealign: config_getval(key logfilename) returned no value\n");
        exit(0);
    }
    p_log_simple("awesome0\n");
    strcpy(logfilename, log_dir);
    strcat(logfilename, "/");
    strcat(logfilename, config_value);
    sprintf(command, "%d", fcnum);
    strcat(logfilename, command);
    strcat(logfilename, ".log");
    p_log_simple(logfilename);
    start_logger(logfilename, 1);

    strcpy(offsetfilename, log_dir);
    strcat(offsetfilename, "/");
    strcat(offsetfilename, config_value);
    strcat(offsetfilename, command);
    strcat(offsetfilename, ".offsetlog");
    fprintf(stdout, offsetfilename);
    fflush(stdout);
    /*
    if this is being run in 'initialize mode' -- the first scan of a run --
    overwrite the offset logfile
    */
    p_log_simple("awesome66\n");
    if(initialize){
        offsetfp = fopen(offsetfilename, "w");
    }
    else{
        offsetfp = fopen(offsetfilename, "a");
    }
    p_log_simple("awesome00\n");
    if(!config_getvalue("stagealign_baseimgfilename", config_value)){
        p_log("ERROR:\tPolonator-stagealign: config_getval(key stagealign_baseimgfilename) returned no value");
        exit(0);
    }
    sprintf(stagealign_baseimgfilename, "%s/%s%s_%d.raw", output_directory, config_value, command, lane_num);
    p_log_simple("awesome01\n");
    if(!config_getvalue("stagealign_integration_inmsec", config_value)){
        p_log("ERROR:\tPolonator-stagealign: config_getval(key stagealign_integration_inmsec) returned no value");
        exit(0);
    }
    stagealign_integration_inmsec = atoi(config_value);
    p_log_simple("awesome02\n");
    if(!config_getvalue("stagealign_gain", config_value)){
        p_log("ERROR:\tPolonator-stagealign: config_getval(key stagealign_gain) returned no value");
        exit(0);
    }
    stagealign_gain = atoi(config_value);
    p_log_simple("awesome03\n");
    if(!config_getvalue("stagealign_optical_mag", config_value)){
        p_log("ERROR:\tPolonator-stagealign: config_getval(key stagealign_optical_mag) returned no value");
        exit(0);
    }
    stagealign_optical_mag = atoi(config_value);
    p_log_simple("awesome04\n");
    if(!config_getvalue("stagealign_ccd_pixel_size", config_value)){
        p_log("ERROR:\tPolonator-stagealign: config_getval(key stagealign_ccd_pixel_size) returned no value");
        exit(0);
    }
    ccd_pixel_size = atoi(config_value);
    p_log_simple("awesome05\n");
    if(!config_getvalue("stagealign_wells_per_fc", config_value)){
        p_log("ERROR:\tPolonator-stagealign: config_getval(key stagealign_wells_per_fc) returned no value");
        exit(0);
    }
    stagealign_wells_per_fc = atoi(config_value);
    config_close();
    p_log_simple("awesome06\n");
    stagealign_well = lane_num;
    lane_index = (fcnum * stagealign_wells_per_fc) + stagealign_well;


    baseimage = (short unsigned int*)malloc(1000000 * sizeof(short unsigned int));

    /*--------------------------------------------------------------------------
    //
    // MAESTRO SETUP
    /*/
    p_log_simple("STATUS:\tPolonator-stagealign: Opening connection to Maestro...");
    maestro_open(&m_sock);
    /*
    //--------------------------------------------------------------------------
    */


    /*--------------------------------------------------------------------------
    //
    // CAMERA SETUP
    /*/
    p_log_simple("STATUS:\tPolonator-stagealign: Opening camera handle...");
    py_cameraInit(0); /* use non-TDI config file */
    py_set_gain(stagealign_gain);
    py_setupSnap(); /* setup capture software to wait for images from camera */
    /*
    //--------------------------------------------------------------------------
    */


    /*p_log("STATUS:\tPolonator-stagealign: Darkfield illuminator on...");  rolony*/
    /*maestro_darkfield_on(m_sock);
    p_log("STATUS:\tPolonator-stagealign: Select darkfield filter block...");  rolony*/
    maestro_setcolor(m_sock, "cy5");


    /* IF INITIALIZING, RESET OFFSETS */
    if(initialize){
        p_log_simple("INITIALIZING STAGEALIGN");
        sprintf(command, "PolonatorScan.OFFSET_X[%d]=0\n\r", lane_index);
        p_log_simple(command);
        send(m_sock, command, strlen(command), 0);
        maestro_readresponse(m_sock, response, &response_length);
        p_log_simple(response);

        sprintf(command, "PolonatorScan.OFFSET_Y[%d]=0\n\r", lane_index);
        p_log_simple(command);
        send(m_sock, command, strlen(command), 0);
        maestro_readresponse(m_sock, response, &response_length);
        p_log_simple(response);
    }
    /* GET OFFSETS IN CASE ALIGNMENT FAILS */
    else{
        p_log_simple("Storing current offsets...");
        sprintf(command, "PolonatorScan.OFFSET_X[%d]\n\r", lane_index);
        p_log_simple(command);
        send(m_sock, command, strlen(command), 0);
        maestro_readresponse(m_sock, response, &response_length);
        p_log_simple(response);
        curr_offset_x = atoi(response);

        sprintf(command, "PolonatorScan.OFFSET_Y[%d]\n\r", lane_index);
        p_log_simple(command);
        send(m_sock, command, strlen(command), 0);
        maestro_readresponse(m_sock, response, &response_length);
        p_log_simple(response);
        curr_offset_y = atoi(response);
    }

    /* MOVE STAGE TO ORIGIN */
    maestro_gotostagealign_position(m_sock, fcnum, lane_num);

    p_log_simple("awesome fool00\n");
    /* ACQUIRE IMAGE */
    p_log("STATUS:\tPolonator-stagealign: Acquire image...");
    maestro_snap(m_sock, stagealign_integration_inmsec, 1); /*rolony*/
    while(!py_snapReceived()){;}
    testimage = py_getSnapImage();


    /* IF INITIALIZING, RE-WRITE THE BASE IMAGE; THE OFFSET FOUND SHOULD BE ZERO */
    p_log_simple(stagealign_baseimgfilename);
    if(initialize){
        baseimgfp = fopen(stagealign_baseimgfilename, "w");
        fwrite(testimage, 1000000, sizeof(short unsigned int), baseimgfp);
        fclose(baseimgfp);
    }
    p_log_simple("awesome fool01\n");
#ifdef DEBUG_STAGEALIGN
    fwrite(testimage, 1000000, sizeof(short unsigned int), imgfp);
#endif

    /* LOAD BASE IMAGE */
    p_log("STATUS:\tPolonator-stagealign: Load base image and determine offset...");
    baseimgfp = fopen(stagealign_baseimgfilename, "r");
    fread(baseimage, 1000000, sizeof(short unsigned int), baseimgfp);
    fclose(baseimgfp);
    p_log("STATUS:\tPolonator-stagealign: Load base image and determine offset2...");

    /* DETERMINE OFFSETS */
    register_image(baseimage, testimage, &pixel_offset_x, &pixel_offset_y, &score, score_matrixfp);
    sprintf(log_string, "STATUS:\tPolonator-stagealign: Found pixel offsets X:%d, Y:%d, score:%d", pixel_offset_x, pixel_offset_y, score);
    p_log(log_string);


    /* LOAD ENCODER RESOLUTIONS FOR CONVERSION BELOW; THESE ARE STORED ON */
    /* THE CONTROLLER AS COUNTS PER MILLIMETER */
    p_log("Retrieving encoder resolutions...");
    sprintf(command, "PolonatorScan.cENCODER_X_RESOLUTION\n\r");
    p_log(command);
    send(m_sock, command, strlen(command), 0);
    maestro_readresponse(m_sock, response, &response_length);
    p_log(response);
    encoder_res_X = atof(response);

    sprintf(command, "PolonatorScan.cENCODER_Y_RESOLUTION\n\r");
    p_log(command);
    send(m_sock, command, strlen(command), 0);
    maestro_readresponse(m_sock, response, &response_length);
    p_log(response);
    encoder_res_Y = atof(response);


    /* CONVERT FROM PIXELS TO STAGE UNITS */
    /* CALCULATE PIXEL SIZE IN MILLIMTERS AT THE STAGE BASED */
    /* ON THE MAGNIFICATION AND THE CCD PIXEL SIZE */
    pixelsize_at_stage = ((double)ccd_pixel_size / (double)stagealign_optical_mag) / 1000;
    stageunit_offset_x = (double)pixel_offset_x * pixelsize_at_stage * encoder_res_X * -1;
    stageunit_offset_y = (double)pixel_offset_y * pixelsize_at_stage * encoder_res_Y * -1;


    /* SET NEW OFFSETS ON CONTROLLER USING VALUES */
    /* CALCULATED ABOVE */
    sprintf(command, "PolonatorScan.OFFSET_X[%d]\n\r", lane_index);
    send(m_sock, command, strlen(command), 0);
    maestro_readresponse(m_sock, response, &response_length);
    fprintf(offsetfp, "%d\t%d\t", fcnum, stagealign_well);
    fprintf(offsetfp, "%d\t", atoi(response));
    sprintf(command, "PolonatorScan.OFFSET_Y[%d]\n\r", lane_index);
    send(m_sock, command, strlen(command), 0);
    maestro_readresponse(m_sock, response, &response_length);
    fprintf(offsetfp, "%d\t", atoi(response));
    fprintf(offsetfp, "%d\t%d\t%d\t%d\t", (int)stageunit_offset_x, (int)stageunit_offset_y, pixel_offset_x, pixel_offset_y);


    /* ISSUE COMMANDS TO ADJUST STAGE COORDS */
    p_log("STATUS:\tPolonator-stagealign: Set offset variables on Maestro...");
    sprintf(command, "PolonatorScan.OFFSET_X[%d]=PolonatorScan.OFFSET_X[%d]+%d\n\r", lane_index, lane_index, (int)stageunit_offset_x);
    p_log(command);
    send(m_sock, command, strlen(command), 0);
    maestro_readresponse(m_sock, response, &response_length);
    p_log(response);

    sprintf(command, "PolonatorScan.OFFSET_Y[%d]=PolonatorScan.OFFSET_Y[%d]+%d\n\r", lane_index, lane_index, (int)stageunit_offset_y);
    p_log(command);
    send(m_sock, command, strlen(command), 0);
    maestro_readresponse(m_sock, response, &response_length);
    p_log(response);


    /* MOVE, THEN ACQUIRE ANOTHER IMAGE TO VERIFY OFFSET WORKED */
    /* maestro_gotostagealign_position(m_sock, fcnum, lane_num);
    maestro_snap(m_sock, stagealign_integration_inmsec, 0);
    while(!py_snapReceived()){;}
    testimage = py_getSnapImage();
    */

#ifdef DEBUG_STAGEALIGN
    fwrite(testimage, 1000000, sizeof(short unsigned int), imgfp);
    fclose(imgfp);
#endif


    /* DETERMINE OFFSET TO CONFIRM */
    /* p_log("STATUS:\tPolonator-stagealign: Re-compute alignment to verify move...");
    register_image(baseimage, testimage, &pixel_offset_x, &pixel_offset_y, &score, score_matrixfp);
    sprintf(log_string, "STATUS:\tPolonator-stagealign: Found pixel offsets X:%d, Y:%d, score:%d", pixel_offset_x, pixel_offset_y, score);
    p_log(log_string);
    fprintf(offsetfp, "%d\t%d", pixel_offset_x, pixel_offset_y);
    */

    /* DID THE MOVE WORK? */
    if(((abs(pixel_offset_x)>successful_move_threshold) || (abs(pixel_offset_y)>successful_move_threshold)) && (!initialize))
    {
        sprintf(log_string, "ERROR:\tPolonator-stagealign: one or more offsets are greater that the %d-pixel maximum; X:%d, Y:%d",
            successful_move_threshold,
            pixel_offset_x,
            pixel_offset_y);
        p_log(log_string);
        fprintf(offsetfp, "*");
        /* mark current line in offsetlog, since offsets found will not be the offsets stored on the controller */

        sprintf(log_string, "Restoring previous offsets X:%d, Y:%d", curr_offset_x, curr_offset_y);


        sprintf(command, "PolonatorScan.OFFSET_X[%d]=%d\n\r", lane_index, curr_offset_x);
        p_log(command);
        send(m_sock, command, strlen(command), 0);
        maestro_readresponse(m_sock, response, &response_length);
        p_log(response);

        sprintf(command, "PolonatorScan.OFFSET_Y[%d]=%d\n\r", lane_index, curr_offset_y);
        p_log(command);
        send(m_sock, command, strlen(command), 0);
        maestro_readresponse(m_sock, response, &response_length);
        p_log(response);
    }

    /* EXIT */
#ifdef DEBUG_STAGEALIGN
    fclose(score_matrixfp);
#endif
    fprintf(offsetfp, "\n");
    fclose(offsetfp);
    /*maestro_darkfield_off(m_sock); rolony*/
    py_cameraClose();
    free(baseimage);
    close_logger();
    p_log_simple("awesome fool02\n");
}
Beispiel #7
0
int main(int argc, char **argv) {
	int ncmds, i;
	const char *tmp;
	pgm_error_t *pgm_err = NULL;

	/* FIXME */
	signal(SIGPIPE, SIG_IGN);
	setup_signal_handlers();
	cmds = table_new(cmpstr, hashmurmur2, NULL, NULL);
	ncmds = sizeof commands / sizeof (struct cmd);
	for (i = 0; i < ncmds; ++i) {
		struct cmd *cmd = commands + i;

		table_insert(cmds, cmd->name, cmd);
	}
	if (argc != 2 && argc != 3)
		usage();
	else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))
		usage();
	else if (argc == 3 && strcmp(argv[1], "-f"))
		usage();
	if (argc == 2 && daemon(1, 0) == -1)
		fprintf(stderr, "Error daemonizing: %s\n", strerror(errno));
	/* FIXME */
	if (init_logger("/var/log/xcb/xcb-dp2.log", __LOG_DEBUG) == -1) {
		fprintf(stderr, "Error initializing logger\n");
		exit(1);
	}
	cfg_path = argc == 2 ? argv[1] : argv[2];
	if ((cfg = config_load(cfg_path)) == NULL)
		exit(1);
	if ((tmp = variable_retrieve(cfg, "general", "log_level"))) {
		if (!strcasecmp(tmp, "info"))
			set_logger_level(__LOG_INFO);
		else if (!strcasecmp(tmp, "notice"))
			set_logger_level(__LOG_NOTICE);
		else if (!strcasecmp(tmp, "warning"))
			set_logger_level(__LOG_WARNING);
	}
	/* FIXME */
	if (addms)
		times = table_new(cmpstr, hashmurmur2, kfree, vfree);
	clients_to_close = dlist_new(NULL, NULL);
	clients = dlist_new(NULL, NULL);
	monitors = dlist_new(NULL, NULL);
	tp = thrpool_new(16, 512, 200, NULL);
	if (!pgm_init(&pgm_err)) {
		xcb_log(XCB_LOG_ERROR, "Error starting PGM engine: %s", pgm_err->message);
		pgm_error_free(pgm_err);
		goto err;
	}
	/* FIXME */
	if (NEW(pgm_send_cfg) == NULL) {
		xcb_log(XCB_LOG_ERROR, "Error allocating memory for PGM cfg");
		goto err;
	}
	pgm_send_cfg->network = NULL;
	pgm_send_cfg->port    = 0;
	init_pgm_send_cfg(pgm_send_cfg);
	if (pgm_send_cfg->network == NULL) {
		xcb_log(XCB_LOG_ERROR, "PGM network can't be NULL");
		goto err;
	}
	if (pgm_send_cfg->port == 0) {
		xcb_log(XCB_LOG_ERROR, "PGM port can't be zero");
		goto err;
	}
	if ((pgm_sender = pgmsock_create(pgm_send_cfg->network, pgm_send_cfg->port, PGMSOCK_SENDER)) == NULL)
		goto err;
	/* FIXME */
	if ((el = create_event_loop(1024 + 1000)) == NULL) {
		xcb_log(XCB_LOG_ERROR, "Error creating event loop");
		goto err;
	}
	create_time_event(el, 1, server_cron, NULL, NULL);
	if ((tmp = variable_retrieve(cfg, "general", "udp_port")) && strcmp(tmp, "")) {
		if ((udpsock = net_udp_server(NULL, atoi(tmp), neterr, sizeof neterr)) == -1) {
			xcb_log(XCB_LOG_ERROR, "Opening port '%s': %s", tmp, neterr);
			goto err;
		}
		if (net_nonblock(udpsock, neterr, sizeof neterr) == -1) {
			xcb_log(XCB_LOG_ERROR, "Setting port '%s' nonblocking: %s", tmp, neterr);
			goto err;
		}
	}
	if ((tmp = variable_retrieve(cfg, "general", "tcp_port")) && strcmp(tmp, ""))
		if ((tcpsock = net_tcp_server(NULL, atoi(tmp), neterr, sizeof neterr)) == -1) {
			xcb_log(XCB_LOG_ERROR, "Opening port '%s': %s", tmp, neterr);
			goto err;
		}
	if (udpsock > 0 && create_file_event(el, udpsock, EVENT_READABLE, read_quote, NULL) == -1) {
		xcb_log(XCB_LOG_ERROR, "Unrecoverable error creating udpsock '%d' file event", udpsock);
		goto err;
	}
	if (tcpsock > 0 && create_file_event(el, tcpsock, EVENT_READABLE, tcp_accept_handler, NULL) == -1) {
		xcb_log(XCB_LOG_ERROR, "Unrecoverable error creating tcpsock '%d' file event", tcpsock);
		goto err;
	}
	xcb_log(XCB_LOG_NOTICE, "Server dispatcher started");
	start_event_loop(el, ALL_EVENTS);
	delete_event_loop(el);
	pgm_shutdown();
	return 0;

err:
	close_logger();
	exit(1);
}
Beispiel #8
0
static int server_cron(event_loop el, unsigned long id, void *data) {
	dlist_iter_t iter;
	dlist_node_t node;
	NOT_USED(el);
	NOT_USED(id);
	NOT_USED(data);

	if (log_reload) {
		close_logger();
		if (init_logger("/var/log/xcb/xcb-dp2.log", __LOG_DEBUG) == 0) {
			const char *tmp;

			pthread_mutex_lock(&cfg_lock);
			if ((tmp = variable_retrieve(cfg, "general", "log_level"))) {
				if (!strcasecmp(tmp, "debug"))
					set_logger_level(__LOG_DEBUG);
				else if (!strcasecmp(tmp, "info"))
					set_logger_level(__LOG_INFO);
				else if (!strcasecmp(tmp, "notice"))
					set_logger_level(__LOG_NOTICE);
				else if (!strcasecmp(tmp, "warning"))
					set_logger_level(__LOG_WARNING);
			}
			pthread_mutex_unlock(&cfg_lock);
			log_reload = 0;
		}
		/* FIXME */
		if (addms)
			table_clear(times);
	}
	if (shut_down) {
		if (prepare_for_shutdown() == 0)
			exit(0);
		xcb_log(XCB_LOG_WARNING, "SIGTERM received, but errors trying to shutdown the server");
	}
	/* FIXME */
	iter = dlist_iter_new(clients_to_close, DLIST_START_HEAD);
	while ((node = dlist_next(iter))) {
		client c = (client)dlist_node_value(node);

		if (c->refcount == 0)
			client_free(c);
	}
	dlist_iter_free(&iter);
	/* FIXME */
	if (cronloops % 200 == 0) {
		char meme[] = "SU OT GNOLEB ERA ESAB RUOY LLA";
		int status;

		/* heartbeat */
		dlist_lock(clients);
		if (dlist_length(clients) > 0) {
			dstr res = dstr_new("HEARTBEAT|");
			dstr ip = getipv4();

			res = dstr_cat(res, ip);
			res = dstr_cat(res, "\r\n");
			iter = dlist_iter_new(clients, DLIST_START_HEAD);
			while ((node = dlist_next(iter))) {
				client c = (client)dlist_node_value(node);

				pthread_spin_lock(&c->lock);
				if (net_try_write(c->fd, res, dstr_length(res), 100, NET_NONBLOCK) == -1)
					xcb_log(XCB_LOG_WARNING, "Writing to client '%p': %s",
						c, strerror(errno));
				pthread_spin_unlock(&c->lock);
			}
			dlist_iter_free(&iter);
			dstr_free(ip);
			dstr_free(res);
		}
		dlist_unlock(clients);
		/* FIXME: trying to lower the high CPU load while idle */
		if ((status = pgm_send(pgm_sender, meme, sizeof meme, NULL)) != PGM_IO_STATUS_NORMAL)
			xcb_log(XCB_LOG_WARNING, "Communication test failed");
	}
	++cronloops;
	return 100;
}
int main(int argc, char **argv) {
  int status, scene, next_scene;
  char errmsg[128];
  long elapsed_msec, wait_msec;
  struct timespec wait_time, left_time;
  struct timeval frame_start_time, frame_end_time;
  WINDOW *window;
  struct invaders_game game;
  struct logger error_logger;

  UNUSED(argc);
  UNUSED(argv);

  /* Initialize for ncurses library */
  reset_logger(&error_logger, ERRORLOG_FILEPATH);
  status = 1;
  window = initscr();
  if (ERR == wresize(window, CANVAS_SIZE_X, CANVAS_SIZE_Y)) {
    emit_log(&error_logger,
             "Failed to change the ncurses setting for window size");
    goto cleanup;
  }
  if (ERR == keypad(window, true)) {
    emit_log(&error_logger,
             "Failed to change the ncurses setting for key input receiving");
    goto cleanup;
  }
  if (ERR == noecho()) {
    emit_log(&error_logger,
             "Failed to change the ncurses setting for echoing setting");
    goto cleanup;
  }
  curs_set(0);
  timeout(0);
  if (has_colors() && can_change_color()) {
    if (ERR == start_color()) {
      emit_log(&error_logger,
               "Failed to change the ncurses setting to set up coloring");
      goto cleanup;
    }
    if ((ERR == init_pair(PLAYER_JET_COLOR_PAIR, PLAYER_JET_COLOR, COLOR_BLACK))
        || (ERR == init_pair(PLAYER_BULLET_COLOR_PAIR, PLAYER_BULLET_COLOR,
        COLOR_BLACK))
        || (ERR == init_pair(TOCHCA_COLOR_PAIR, TOCHCA_COLOR, COLOR_BLACK))
        || (ERR == init_pair(COMMANDER_INVADER_COLOR_PAIR, COMMANDER_INVADER_COLOR,
            COLOR_BLACK))
        || (ERR == init_pair(SENIOR_INVADER_COLOR_PAIR, SENIOR_INVADER_COLOR,
        COLOR_BLACK))
        || (ERR == init_pair(YOUNG_INVADER_COLOR_PAIR, YOUNG_INVADER_COLOR,
        COLOR_BLACK))
        || (ERR == init_pair(LOOKIE_INVADER_COLOR_PAIR, LOOKIE_INVADER_COLOR,
        COLOR_BLACK))
        || (ERR == init_pair(INVADER_BULLET_COLOR_PAIR, INVADER_BULLET_COLOR,
        COLOR_BLACK))
        || (ERR == init_pair(TITLE_COLOR_PAIR, TITLE_COLOR, COLOR_BLACK))
        || (ERR == init_pair(EVENT_CAPTION_COLOR_PAIR, EVENT_CAPTION_COLOR,
        COLOR_BLACK))
        || (ERR == init_pair(SCORE_COLOR_PAIR, SCORE_COLOR, COLOR_BLACK))
        || (ERR == init_pair(CREDIT_COLOR_PAIR, CREDIT_COLOR, COLOR_BLACK))
        || (ERR
            == init_pair(CANVAS_FRAME_COLOR_PAIR, CANVAS_FRAME_COLOR, COLOR_BLACK))) {
      emit_log(&error_logger,
               "Failed to change the ncurses setting to define color pair");
      goto cleanup;
    }

  }

  /* Execute game loop */
  scene = -1;
  next_scene = TITLE_SCENE;
  while (1) {
    /* Record the frame starting time */
    if (0 != gettimeofday(&frame_start_time, NULL)) {
      emit_log(&error_logger, "Failed to get time of frame starting");
      goto cleanup;
    }

    /* Change the next scene if needed */
    if (scene != next_scene) {
      scene = next_scene;
      if (INGAME_SCENE == scene) {
        reset_game(&game);
      }
    }

    /* Update the objects */
    if (TITLE_SCENE == scene) {
      update_game_on_title_scene(&next_scene);
    } else if (INGAME_SCENE == scene) {
      update_game_on_ingame_scene(&game, IDEAL_FRAME_TIME, &next_scene);
    }

    /* Render the objects */
    erase();
    if (TITLE_SCENE == scene) {
      draw_title_scene();
    } else if (INGAME_SCENE == scene) {
      draw_ingame_scene(&game);
    }
    draw_canvas_frame();
    refresh();

    /* Adjust the frame interval */
    if (0 != gettimeofday(&frame_end_time, NULL)) {
      emit_log(&error_logger, "Failed to get time of frame finished");
      goto cleanup;
    }
    elapsed_msec = (frame_end_time.tv_sec - frame_start_time.tv_sec) * 1000L
        + (frame_end_time.tv_usec - frame_start_time.tv_usec) / 1000000L;
    wait_msec = IDEAL_FRAME_TIME - elapsed_msec;
    if (0L < wait_msec) {
      wait_time.tv_sec = 0;
      wait_time.tv_nsec = wait_msec * 1000000L;
      while (-1 == nanosleep(&wait_time, &left_time)) {
        if (EINTR == errno) {
          memcpy(&wait_time, &left_time, sizeof(struct timespec));
        } else {
          if (0 == strerror_r(errno, errmsg, sizeof(errmsg))) {
            emit_log(
                &error_logger,
                "Failed to sleep until the end of frame: errmsg=%s, sleeping_msec=%ld",
                errmsg, wait_msec);
          } else {
            emit_log(&error_logger, "Failed to get error message: errno=%d",
            errno);
          }
          goto cleanup;
        }
      }
    }
  }
  status = 0;

 cleanup:
  endwin();
  close_logger(&error_logger);
  return status;
}
Beispiel #10
0
Datei: main.c Projekt: taysom/tau
void close_db(struct db *db)
{
    close_logger(db->w);
    close_reader(db->r);
    free_bag(db->bag);
}