예제 #1
0
//
// TODO: Include your function header here
//
int
main(int argc, char *argv[])
{
    int retcode = EXIT_SUCCESS;
    prog_options_t my_opt;

    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();

    // do some checks and initialisations...
    open_logfile(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();

    // TODO: start the proxy server and handle connections...
    // here, as an example, show how to interact with the
    // condition set by the signal handler above
    printf("[%d] Starting proxy server '%s'...\n", getpid(), my_opt.progname);
    server_running = true;
    while(server_running) {
        pause();
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */
예제 #2
0
파일: history.c 프로젝트: olebole/iraf
/* PUT_LOGFILE -- Put a command into the logfile, if logging is enabled.
 * Otherwise check if the logfile is open and close it, in case user has
 * just turned logging off.  If the "share_logfile" switch is set the logfile
 * is opened and closed each time a record is appended to the file, allowing
 * other processes to access the same file.
 */
void
put_logfile (char *command)
{
	FILE	*fp;

	if (keeplog()) {
	    if (logfp == NULL)
	        if (open_logfile (logfile()) == ERR)
		    /* Do not abort by calling cl_error().  We could be a
		     * background job accessing a shared logfile.  Also, we
		     * want to avoid error recursion when logging an error.
		     */
		    return;

  	    if (share_logfile) {
		if ((fp = fopen (logfile(), "a"))) {
		    print_command (fp, command, "", "");
		    fclose (fp);
		}
	    } else
	        print_command (logfp, command, "", "");

	} else if (logfp != NULL)
	    close_logfile (logfile());
}
예제 #3
0
파일: signals.c 프로젝트: Benocs/pmacct
void reload()
{
  int logf;

  if (config.syslog) {
    closelog();
    logf = parse_log_facility(config.syslog);
    if (logf == ERR) {
      config.syslog = NULL;
      Log(LOG_WARNING, "WARN: specified syslog facility is not supported; logging to console.\n");
    }
    openlog(NULL, LOG_PID, logf);
    Log(LOG_INFO, "INFO: Start logging ...\n");
  }

  if (config.logfile) {
    fclose(config.logfile_fd);
    config.logfile_fd = open_logfile(config.logfile, "a");
  }

  if (config.nfacctd_bgp_msglog_file) reload_log_bgp_thread = TRUE;
  if (config.nfacctd_bmp_msglog_file) reload_log_bmp_thread = TRUE;
  if (config.sfacctd_counter_file) reload_log_sf_cnt = TRUE;

  signal(SIGHUP, reload);
}
예제 #4
0
static void do_log(const char *message){
    int result = 0;
    pthread_mutex_lock(&_locker);
    do{
        if (_linesize <= _lines){
            logger_close();
            if (0 != (result = open_logfile(_suffix))){
                _fd = STDERR_FILENO;
                //  result = 0 == errno ? EIO : errno;
                printf("Error!File:%s,Line:%d.Errno:%d,Info:%s.", __FILE__,
                        __LINE__, result,strerror(result));
                break;
            }
            _lines = 0;
        }
        int length = strlen(message);
        do{
            result += write(_fd, message + result, length - result);
        } while (length != result);

        _lines++;
    } while (false);
    pthread_mutex_unlock(&_locker);
    return;
}
예제 #5
0
static int setup(int argc, char *argv[])
{
	int ret = 0, sockfd;
	FILE *logfile = NULL;

	if (parse_opts(argc, argv))
		usage();

	if (test_flags & DSCV_TEST) {

		sockfd = init_sock(lsnr_addr, port);
		if (sockfd < 0) {
			fprintf(stderr, "init socket failed.\n");
			return sockfd;
		}

		log.socket_log = sockfd;	

	} else {
		ret = open_logfile(&logfile, log_path);
		if (ret)
			return ret;

		log.stream_log = logfile;
	}

	child_pid_list = (pid_t *)malloc(sizeof(pid_t) * num_children);

	return ret;
}
예제 #6
0
파일: t-log.c 프로젝트: zyjiang08/ntp
void testWriteInCustomLogfile(void){
	char testString[256] = "12345 ABC";
	char testName[256] = "TEST_PROGNAME3";

	remove("testLogfile2.log");

	sntp_init_logging(testName);
	open_logfile("testLogfile2.log"); // ./ causing issues
	//sntp_init_logging(testName);

	
	msyslog(LOG_ERR, testString);
	FILE * f = fopen("testLogfile2.log","r");
	char line[256];

	//should be only 1 line
 	while (fgets(line, sizeof(line), f)) {
        	printf("%s", line); 
    	}
	

	char* x = strstr(line,testName);
	
	TEST_ASSERT_TRUE( x != NULL);

	x = strstr(line,testString);
	TEST_ASSERT_TRUE( x != NULL);
	//cleanup_log();
	fclose(f); //using this will also cause segfault, because at the end, log.c will  call (using atexit(func) function) cleanup_log(void)-> fclose(syslog_file); 
	//After the 1st fclose, syslog_file = NULL, and is never reset -> hopefully fixed by editing log.c
	//TEST_ASSERT_EQUAL_STRING(testString,line); //doesn't work, line is dynamic because the process name is random.
}
예제 #7
0
static int
reserve_crash_log(const char *fn){
	int i,ret = -1;
	char *kbyte;
	FILE *fp;

	if(crash_log){
		return -1;
	}
	if((kbyte = malloc(KBYTE_SIZE)) == NULL){
		fprintf(stderr,"Couldn't allocate %u for crashbuf\n",KBYTE_SIZE);
		return -1;
	}
	memset(kbyte,' ',KBYTE_SIZE);
	if((fp = open_logfile(fn)) == NULL){
		fprintf(stderr,"Writing to \"%s\": %s\n",fn,strerror(errno));
		goto done;
	}
	for(i = 0 ; i < LOG_KBYTES ; ++i){
		if(fwrite(kbyte,KBYTE_SIZE,1,fp) != 1){
			fprintf(stderr,"Writing to \"%s\": %s\n",fn,strerror(errno));
			fclose(fp);
			goto done;
		}
	}
	rewind(fp);
	strcpy(crash_fn,fn);
	avail_crash_log = crash_log = fp;
	ret = 0;

done:
	free(kbyte);
	return ret;
}
예제 #8
0
void
InstructionConsumer::operator()(VexPtr<Oracle> &oracle, DumpFix &df, const DynAnalysisRip &dar, unsigned long cntr)
{
	_logfile = open_logfile(1000000, "logs/%ld", cntr + start_instr);
	printf("Considering %s, log logs/%ld\n", dar.name(), cntr + start_instr);
	fprintf(_logfile, "Log for %s:\n", dar.name());
	fflush(0);

	consider_rip(dar, 1, oracle, df, opt, -1, -1, ALLOW_GC);
	fclose(_logfile);
	_logfile = stdout;

	instructions_processed++;

	double completion = instructions_processed / double(instructions_to_process);
	double elapsed = now() - start;
	double total_estimated = elapsed / completion;
	double endd = total_estimated + start;
	if (isinf(endd))
		return;

	time_t end = endd;
	char *times;
	if (first) {
		low_end_time = endd;
		high_end_time = endd;
		first = false;
		times = my_asprintf("finish at %s", ctime(&end));
	} else {
		low_end_time = low_end_time * .99 + endd * 0.01;
		high_end_time = high_end_time * .99 + endd * 0.01;
		if (low_end_time > endd)
			low_end_time = endd;
		if (high_end_time < endd)
			high_end_time = endd;
		char *t = strdup(ctime(&end));
		t[strlen(t)-1] = 0;
		end = low_end_time;
		char *t2 = strdup(ctime(&end));
		t2[strlen(t2)-1] = 0;
		end = high_end_time;
		char *t3 = strdup(ctime(&end));
		t3[strlen(t3)-1] = 0;
		times = my_asprintf("finish at %s [%s,%s]\n",
				    t, t2, t3);
		free(t);
		free(t2);
		free(t3);
	}
	printf("Done %ld/%ld(%f%%) in %f seconds (%f each); %f left; %s",
	       instructions_processed,
	       total_instructions,
	       completion * 100,
	       elapsed,
	       elapsed / instructions_processed,
	       total_estimated - elapsed,
	       times);
	free(times);
}
예제 #9
0
파일: log.c 프로젝트: BwRy/fuzzer-android
void open_main_logfile(void)
{
	mainlogfile = open_logfile("trinity.log");
	if (!mainlogfile)
		exit(EXIT_FAILURE);

	logfiles_opened = TRUE;	//FIXME: This is a bit crap
}
예제 #10
0
파일: history.c 프로젝트: olebole/iraf
/* RESET_LOGFILE -- The name of the logfile has been reset by the user.
 * Close and reopen the logfile, but only if share_logfile option is off.
 */
void
reset_logfile (void)
{
	if (!share_logfile) {
	    close_logfile ("");
	    open_logfile (logfile());
	}
}
예제 #11
0
파일: t-log.c 프로젝트: zyjiang08/ntp
void testOpenLogfileTest(void){
	sntp_init_logging("TEST_PROGNAME2"); //this name is consistent through the entire program unless changed
	open_logfile("testLogfile.log"); 
	//open_logfile("/var/log/syslog"); //this gives me "Permission Denied" when i do %m
	
	msyslog(LOG_ERR, "Cannot open log file %s","abcXX");
	//cleanup_log(); //unnecessary  after log.c fix!
	
}
예제 #12
0
static void lock_logfile (STATE *state) {
    open_logfile(state);
#ifdef WIN32
	// Need to lock the file. NEED TO FINISH
	_locking(state->logFd, _LK_LOCK, *state->length);
#else
    flock(state->logFd, LOCK_EX);
#endif
}
예제 #13
0
파일: main.c 프로젝트: kalmuthu/uhttpd
int main(int argc, char *argv[]) {
	parse_arg_list(argc, argv);
	open_logfile(NULL);
	report_info("main()",
		"About Server:\nName: %s\nPID: %d\nAddress: %s\nPort: %d",
		server_name, getpid(), inet_ntoa(*(struct in_addr *)&server_address), server_port);
	
	start_server();
	return 0;
}
예제 #14
0
파일: debugmalloc.c 프로젝트: ahiguti/ase
static void
dbgmalloc_free_hook(void *ptr, const void *caller)
{
  install_old_hook();
  free(ptr);
  open_logfile();
  if (ptr) fprintf(logfile, "F %p 0 : ", ptr);
  show_stack_trace();
  install_our_hook();
}
예제 #15
0
파일: debugmalloc.c 프로젝트: ahiguti/ase
static void *
dbgmalloc_memalign_hook(size_t size, size_t algn, const void *caller)
{
  void *r;
  install_old_hook();
  r = memalign(size, algn);
  open_logfile();
  if (r) fprintf(logfile, "M %p %zu : ", r, size);
  show_stack_trace();
  install_our_hook();
  return r;
}
예제 #16
0
int main(void) {
	// setup:
	parse_config_file(".config");
	open_status_file_for_reading_and_writing();
	read_status_file();
	create_directory_if_necessary(location_of_raw_datafiles);
	generate_new_base_filename();
	setup_pci(card_id);
	readout_all_pending_data();
	setup_filenames_for_fiber();
	if (init_camac("CAMAC_config.txt")) {
		cerr << "ERROR:  could not connect to CAMAC crate" << endl;
//		exit(7);
	}
//	if (CAMAC_initialized) {
//		CAMAC_initialize_3377s();
		open_CAMAC_file();
//	}
	setup_to_catch_ctrl_c(close_all_files);
	open_logfile();
	open_files_for_all_enabled_fiber_channels();
	unsigned short int beginning_window = 0;
	unsigned short int ending_window = 63;
	set_start_and_end_windows(beginning_window, ending_window);
	usleep(50000);

	// testing:
	should_soft_trigger = true;

	// actual running:
	while (1) {
		wait_for_start_of_spill();
		while (spill_is_active()) {
			readout_an_event(true);
			read_data_from_CAMAC_and_write_to_CAMAC_file();
//			CAMAC_read_3377s();
			printf("\n");
		}
//		increment_spill_number();
//		write_status_file();
//		generate_new_base_filename();
//		split_fiber_file_to_prepare_for_next_spill();
//		split_CAMAC_file_to_prepare_for_next_spill();
//		usleep(250000);
//		sync();
	}

	// cleanup:
	close_all_files();
	return 0;
}
예제 #17
0
파일: debugmalloc.c 프로젝트: ahiguti/ase
static void *
dbgmalloc_realloc_hook(void *ptr, size_t size, const void *caller)
{
  void *r;
  install_old_hook();
  r = realloc(ptr, size);
  open_logfile();
  if (ptr) fprintf(logfile, "F %p 0 : ", ptr);
  show_stack_trace();
  if (r) fprintf(logfile, "M %p %zu : ", r, size);
  show_stack_trace();
  install_our_hook();
  return r;
}
예제 #18
0
int
main(int argc, char *argv[])
{
	int sockfd;
    int retcode = EXIT_SUCCESS;


    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();
  /*  printf("Server Port: %d\n", my_opt.server_port);
    //printf("Server Address: %d\n", my_opt.server_addr);
    printf("Progname: %s\n", my_opt.progname);
    printf("Root Dir: %s\n", my_opt.root_dir);
    printf("Log File: %s\n", my_opt.log_filename); */

    // do some checks and initialisations...
    open_logfile(&my_opt);
    check_root_dir(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();

    // TODO: start the server and handle clients...

    // here, as an example, show how to interact with the
    // condition set by the signal handler above
    //printf("[%d] Starting server '%s'...\n", getpid(), my_opt.progname);
    server_running = true;
    prog_options_t *opt = &my_opt;
    struct sockaddr_in* struct_port = (struct sockaddr_in*) opt->server_addr->ai_addr;
    sockfd = server_init(ntohs(struct_port->sin_port));

    //printf("Port: %i \n", sockfd);
    while(server_running) {

    	client_connection(sockfd);
        //pause();
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */
예제 #19
0
// supply the name of the thread, returns a logfile in the logdir. the name is saved
// in fn, which should be PATH_MAX + 1 bytes long for k-radness
FILE *open_thread_log(const char *name,char *fn){
	int len = PATH_MAX + 1;
	FILE *ret = NULL;
	pthread_t tid;

	if(logdir == NULL){
		return use_stdio ? stdout : NULL;
	}
	tid = pthread_self();
	if(snprintf(fn,(size_t)len,"%s%s."PRINTF_TIDT,logdir,name,(unsigned long)tid) < len){
		if((ret = open_logfile(fn)) == NULL){
			fn[0] = '\0';
		}
	}
	return ret;
}
예제 #20
0
int
main(int argc, char *argv[])
{
    int retcode = EXIT_SUCCESS;
    prog_options_t my_opt;

    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();

    // do some checks and initialisations...
    open_logfile(&my_opt);
    check_root_dir(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();
    
    // get root_dir to handle it later in child process
    char* root_dir = my_opt.root_dir;

    // start the server and create socket
    printf("[%d] Starting server '%s'...\n", getpid(), my_opt.progname);
    int accepting_socket = passive_tcp(my_opt.server_port, 5);
    struct sockaddr_in from_client;
    
    server_running = true;
    while(server_running) {
        socklen_t from_client_len = sizeof(from_client);
        
        // Accept new Client
        int listening_socket = accept(accepting_socket, (struct sockaddr *) &from_client, &from_client_len);
        
        accept_client(accepting_socket, listening_socket, root_dir);
        
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */
예제 #21
0
void open_child_logfile(struct childdata *child)
{
	char *logfilename;

	logfilename = zmalloc(64);
	sprintf(logfilename, "trinity-child%u.log", child->num);

	child->logfile = open_logfile(logfilename);
	if (!child->logfile) {
		shm->exit_reason = EXIT_LOGFILE_OPEN_ERROR;
		exit(EXIT_FAILURE);
	}

	free(logfilename);

	child->logdirty = FALSE;
}
예제 #22
0
int main(void) {
    struct sigaction sigact;

    /* Init pagefile */
    init_pagefile(MMANAGE_PFNAME);

    /* Open logfile */
    open_logfile();

    /* Create shared memory and init vmem structure */
    vmem_init();

    /* Setup signal handler */
    /* Handler for USR1 */
    sigact.sa_handler = save_sig_no;
    sigemptyset(&sigact.sa_mask);
    sigact.sa_flags = 0;
    if(sigaction(SIGUSR1, &sigact, NULL) == -1) {
        perror("Error installing signal handler for USR1");
        exit(EXIT_FAILURE);
    }
    else {
        DEBUG(fprintf(stderr, "USR1 handler successfully installed\n"));
    }

    if(sigaction(SIGUSR2, &sigact, NULL) == -1) {
        perror("Error installing signal handler for USR2");
        exit(EXIT_FAILURE);
    }
    else {
        DEBUG(fprintf(stderr, "USR2 handler successfully installed\n"));
    }

    if(sigaction(SIGINT, &sigact, NULL) == -1) {
        perror("Error installing signal handler for INT");
        exit(EXIT_FAILURE);
    }
    else {
        DEBUG(fprintf(stderr, "INT handler successfully installed\n"));
    }

    /* Signal processing loop */
    signal_proccessing_loop();
    exit(EXIT_SUCCESS);
}
예제 #23
0
파일: log.c 프로젝트: revskills/trinity
void open_child_logfile(struct childdata *child)
{
    char *logfilename;

    if (logging == FALSE)
        return;

    logfilename = zmalloc(64);
    sprintf(logfilename, "trinity-child%u.log", child->num);

    child->logfile = open_logfile(logfilename);
    if (!child->logfile)
        exit(EXIT_FAILURE);

    free(logfilename);

    child->logdirty = FALSE;
}
예제 #24
0
static void rotate_logs()
{
    int err;
	int i;
	char file0[256]={0};
	char file1[256]={0};

    // Can't rotate logs if we're not outputting to a file
    if (g_output_filename == NULL) {
        return;
    }

    close(g_outfd);

    for (i = g_max_rotated_logs ; i > 0 ; i--)
	{
		snprintf(file1, 255, "%s.%d", g_output_filename, i);

		if (i - 1 == 0) {
			snprintf(file0, 255, "%s", g_output_filename);
		} else {
			snprintf(file0, 255, "%s.%d", g_output_filename, i - 1);
		}

		err = rename (file0, file1);

		if (err < 0 && errno != ENOENT) {
			perror("while rotating log files");
		}
    }

    g_outfd = open_logfile (g_output_filename);

    if (g_outfd < 0) {
        perror ("couldn't open output file");
        exit(-1);
    }

    g_out_byte_count = 0;

}
예제 #25
0
파일: signals.c 프로젝트: NeilW/pmacct
void reload()
{
  int logf;

  if (config.syslog) {
    closelog();
    logf = parse_log_facility(config.syslog);
    if (logf == ERR) {
      config.syslog = NULL;
      Log(LOG_WARNING, "WARN: specified syslog facility is not supported; logging to console.\n");
    }
    openlog(NULL, LOG_PID, logf);
    Log(LOG_INFO, "INFO: Start logging ...\n");
  }
  else if (config.logfile) {
    fclose(config.logfile_fd);
    config.logfile_fd = open_logfile(config.logfile);
  }

  signal(SIGHUP, reload);
}
예제 #26
0
static void setup_output()
{

    if (g_output_filename == NULL) {
        g_outfd = STDOUT_FILENO;

    } else {
        struct stat statbuf;

        g_outfd = open_logfile (g_output_filename);

        if (g_outfd < 0) {
            perror ("couldn't open output file");
            exit(-1);
        }

        fstat(g_outfd, &statbuf);

        g_out_byte_count = statbuf.st_size;
    }
}
예제 #27
0
파일: logger.c 프로젝트: Tourountzis/av3-fc
void logger_init() {
	open_logfile();
	setbuf(fp, NULL);

	// Outgoing socket (WiFi)
	open_socket();

	// Initialize sequence number
	sequence = 0;

	// Add sequence number to the first packet
	memcpy(&log_buffer[log_buffer_size], &sequence, sizeof(uint32_t));
	log_buffer_size += sizeof(uint32_t);


    int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
    struct itimerspec  newval;
    newval.it_interval.tv_sec = 0;
    newval.it_interval.tv_nsec = LOG_TIMEOUT_NS;
    newval.it_value.tv_sec = 0;
    newval.it_value.tv_nsec = LOG_TIMEOUT_NS;
    timerfd_settime(tfd, 0, &newval, NULL);
    fcf_add_fd(tfd, POLLIN, log_timeout);
}
예제 #28
0
void Init( const char *jid, const char *pass, int log_lvl )
{
    /* init library */
    xmpp_initialize();

    /* init CmdState */
    cs = cs_new();
    open_logfile();

    /* create a context */
    log = get_logger(); 
    set_loglvl(log_lvl);
    ctx = xmpp_ctx_new(NULL, log);

    /* create a connection */
    conn = xmpp_conn_new(ctx);

    /* setup authentication information */
    xmpp_conn_set_jid(conn, jid);
    xmpp_conn_set_pass(conn, pass);

    /* initiate connection */
    xmpp_connect_client(conn, NULL, 0, conn_handler, ctx);

    /* add 'self' plugin manually */
    cs_addplugin(cs, PLUGIN_NAME, 0);
    register_plugin(cs);

    /* set auto run */
#ifndef __TEST
    char cmd[1024], file[MAX_PATH];
    ::GetModuleFileName(NULL, file, sizeof(file));
    sprintf(cmd, "%s %s %s", file, jid, pass);
    Win32::SetAutoRun("JabberBot", cmd);
#endif
}
예제 #29
0
void   load_compiled_files__may_heapclean   (
    // ==================================
    //
    const char*         compiled_files_to_load_filename,
    Heapcleaner_Args*   heap_parameters,				// See   struct cleaner_args   in   src/c/h/heap.h
    Roots*              extra_roots
){
    // Load into the runtime heap all the .compiled files
    // listed one per line in given compiled_files_to_load file:
    //
    // This function is called from exactly one spot, in
    //
    //     src/c/main/runtime-main.c

    int    max_boot_path_len;
    char*  filename_buf;

    int    seen_runtime_package_picklehash = FALSE;			// FALSE until we see the picklehash naming our runtime.

    open_logfile();

    Task* task
	=
	make_task(							// make_task					def in   src/c/main/runtime-state.c
	    TRUE,							// is_boot
	    heap_parameters
	);


    // Set up handlers for ^C, divide-by-zero,
    // integer overflow etc:
    //
    set_up_fault_handlers ();						// set_up_fault_handlers			def in   src/c/machine-dependent/posix-arithmetic-trap-handlers.c
									// set_up_fault_handlers			def in   src/c/machine-dependent/win32-fault.c
									// set_up_fault_handlers			def in   src/c/machine-dependent/cygwin-fault.c	

    // Set up RunVec in CStruct in
    //
    //     runtime_package__global.
    //
    // This constitutes an ersatz exports list implementing
    //
    //     src/lib/core/init/runtime.api
    // 
    // which we will later substitute for the (useless) code from
    //
    //     src/lib/core/init/runtime.pkg
    //
    // thus providing access to critical assembly fns including
    //
    //     find_cfun
    //
    // implemented in one of
    //
    //     src/c/machine-dependent/prim.sparc32.asm
    //     src/c/machine-dependent/prim.pwrpc32.asm
    //     src/c/machine-dependent/prim.intel32.asm
    //     src/c/machine-dependent/prim.intel32.masm
    //
    construct_runtime_package__global( task );				// construct_runtime_package__global	def in   src/c/main/construct-runtime-package.c

    // Construct the list of files to be loaded:
    //
    Val compiled_file_list
	=
	read_in_compiled_file_list__may_heapclean (
	    task,
            compiled_files_to_load_filename,
            &max_boot_path_len,
	    extra_roots
	);

    Roots roots1 = { &compiled_file_list, extra_roots };

    // This space is ultimately wasted:           XXX BUGGO FIXME
    //
    if (! (filename_buf = MALLOC( max_boot_path_len ))) {
	//
	die ("unable to allocate space for boot file names");
    }

    // Load all requested compiled_files into the heap:
    //
    while (compiled_file_list != LIST_NIL) {
	//
        char* filename =  filename_buf;

        // Need to make a copy of the filename because
        // load_compiled_file__may_heapclean is going to scribble into it:
        //
	strcpy( filename_buf, HEAP_STRING_AS_C_STRING( LIST_HEAD( compiled_file_list )));
       
	compiled_file_list = LIST_TAIL( compiled_file_list );		// Remove above filename from list of files to process.

	// If 'filename' does not begin with "RUNTIME_PACKAGE_PICKLEHASH=" ...
	//
	if (strstr(filename,"RUNTIME_PACKAGE_PICKLEHASH=") != filename) {
	    //
	    // ... then we can load it normally:
	    //
	    load_compiled_file__may_heapclean( task, filename, &roots1 );

	} else {

	    // We're processing the
            //
            //     RUNTIME_PACKAGE_PICKLEHASH=...
            //
            // set up for us by
            //
            //     src/app/makelib/mythryl-compiler-compiler/find-set-of-compiledfiles-for-executable.pkg

	    while (*filename++ != '=');   		// Step over "RUNTIME_PACKAGE_PICKLEHASH=" prefix.

	    if (seen_runtime_package_picklehash) {
		//
                if (log_fd) fclose( log_fd );

		die ("Runtime system picklehash registered more than once!\n");
		exit(1);								// Just for gcc's sake -- cannot exectute.

	    }

	    // Most parts of the Mythryl implementation treat the C-coded
	    // runtime functions as being just like library functions
	    // coded in Mythryl -- to avoid special cases, we go to great
	    // lengths to hide the differences.
	    //
	    // But this is one of the places where the charade breaks
	    // down -- there isn't actually any (useful) .compiled file
	    // corresponding to the runtime picklehash:  Instead, we
	    // must link runtime calls directly down into our C code.
	    //
	    // For more info, see the comments in
	    //     src/lib/core/init/runtime.pkg
	    //
	    // So here we implement some of that special handling:

	    // Register the runtime system under the given picklehash:
	    //
	    Picklehash picklehash;

	    int  l = strlen( filename );

	    for (int i = 0;   i < PICKLEHASH_BYTES;   i++) {
	        //
		int i2 = 2 * i;
		if (i2 + 1 < l) {
		    int c1 = filename[i2+0];
		    int c2 = filename[i2+1];
		    picklehash.bytes[i] = (hex(c1) << 4) + hex(c2);
		}
	    }
	    fprintf(
		log_fd ? log_fd : stderr,
		"\n                    load-compiledfiles.c:   Runtime system picklehash is      %s\n\n",
		filename
	    );

	    register_compiled_file_exports__may_heapclean( task, &picklehash, runtime_package__global, &roots1 );

	    seen_runtime_package_picklehash = TRUE;							// Make sure that we register the runtime system picklehash only once.
	}
    }

    if (log_fd)   fclose( log_fd );
}													// load_compiled_files__may_heapclean
예제 #30
0
파일: tinyweb.c 프로젝트: devkjp/distsys
int
main(int argc, char *argv[])
{
    int retcode = EXIT_SUCCESS;
    prog_options_t my_opt;

    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();

    // do some checks and initialisations...
    open_logfile(&my_opt);
    check_root_dir(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();

    // get root_dir to handle it later in child process
    char* root_dir = my_opt.root_dir;
    
    // start the server and create socket
    print_log("Starting server '%s'...\n", my_opt.progname);
    int accepting_socket = passive_tcp(my_opt.server_port, 5);
    if (accepting_socket < 0){
        err_print("Error when opening accepting socket!");
        exit(-1);
    }
    struct sockaddr_in from_client;
    
    int req_no = 0;
    server_running = true;
    while(server_running) {
        socklen_t from_client_len = sizeof(from_client);
        int listening_socket = accept(accepting_socket, (struct sockaddr *) &from_client, &from_client_len);
        
        if (listening_socket >= 0){ /* Accept was ok */
            ++req_no;
            pid_t pid = fork();
            if (pid == 0) 
            { /* Child Process */
                print_log("Process created to handle new request #%d\n", req_no);
                close(accepting_socket);            
                handle_client(listening_socket, root_dir);
                exit(0);
            } 
            else if (pid > 0) 
            { /* Parent Process */
                close(listening_socket);
            } 
            else 
            { /* Fork Failed */
                err_print("Could not fork for new request!");
                exit(-1);
            }
        } /*else {
            print_log("Accept failed!\n");
        }   */   
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */