Пример #1
0
int
main(int argc, char **argv)
{
    int r;

    progname = argv[0];
    opts(argc, argv);

    job_init();
    prot_init();

    r = make_server_socket(host_addr, port);
    if (r == -1) twarnx("make_server_socket()"), exit(111);

    if (user) su(user);
    if (detach) daemonize();
    event_init();
    set_sig_handlers();
    nudge_fd_limit();

    unbrake((evh) h_accept);

    event_dispatch();
    twarnx("got here for some reason");
    return 0;
}
Пример #2
0
/*
** bmp8 must be grayscale
** (x1,y1) and (x2,y2) from top left of bitmap
*/
void jocr_single_word_from_bmp8(char *text,int maxlen,WILLUSBITMAP *bmp8,
                                int x1,int y1,int x2,int y2,int allow_spaces,
                                int std_proc)

    {
    job_t *job,_job;
    int i,w,h,dw,dh,bw;
    unsigned char *src,*dst;
    // static char *funcname="jocr_single_word_from_bmp8";
    char *buf;
    int pgm2asc(job_t *job);
    char *getTextLine(int);

    if (x1>x2)
        {
        w=x1;
        x1=x2;
        x2=w;
        }
    w=x2-x1+1;
    bw=w/40;
    if (bw<6)
        bw=6;
    dw=w+bw*2;
    if (y1>y2)
        {
        h=y1;
        y1=y2;
        y2=h;
        }
    h=y2-y1+1;
    dh=h+bw*2;
    job=&_job;
    job_init(job);
    job_init_image(job);
    // willus_mem_alloc_warn((void **)&job->src.p.p,w*h,funcname,10);
    /* Must use malloc since job_free_image counts on this. */
    job->src.p.p=malloc(dw*dh);
    job->src.p.x=dw;
    job->src.p.y=dh;
    job->src.p.bpp=1;
    src=bmp_rowptr_from_top(bmp8,y1)+x1;
    memset(job->src.p.p,255,dw*dh);
    dst=(unsigned char *)job->src.p.p + dw*bw + bw;
    for (i=y1;i<=y2;i++,dst+=dw,src+=bmp8->width)
        memcpy(dst,src,w);
    pgm2asc(job);
    buf=getTextLine(0);
    if (buf)
        {
        strncpy(text,buf,maxlen-1);
        text[maxlen-1]='\0';
        if (std_proc)
            ocr_text_proc(text,allow_spaces);
        }
    else
        text[0]='\0';
    // willus_mem_free((double **)&job->src.p.p,funcname);
    job_free_image(job);
    }
Пример #3
0
/* -------------------------------------------------------------
// ------   MAIN - replace this by your own aplication! 
// ------------------------------------------------------------- */
int main(int argn, char *argv[]) {
  int multipnm=1;
  job_t job;

  JOB = &job;
  setvbuf(stdout, (char *) NULL, _IONBF, 0);	/* not buffered */
  
  while (multipnm==1) {

    job_init(&job);
  
    process_arguments(&job, argn, argv);

    mark_start(&job);

    multipnm = read_picture(&job);
    /* separation of main and rest for using as lib
       this will be changed later => introduction of set_option()
       for better communication to the engine  */
    if (multipnm<0) break; /* read error */
  
    /* call main loop */
    pgm2asc(&job);

    mark_end(&job);
  
    print_output(&job);

    job_free(&job);
  
  }
  
  return 0;
}
Пример #4
0
int
main(int argc, char *argv[], char *envp[])
{
	char buff[BUFSIZ];
    int rc;

    signal(SIGTTOU, SIG_IGN);
    signal(SIGINT, sigint_handler);

    rc = setpgid(0, 0);
    assert(rc != -1);


    builtin_init();
    history_init();

    job_init();

    
    print_prompt();
	while (fgets(buff, BUFSIZ, stdin)) {
		job_run_command(buff, envp);

        job_wait();

        print_prompt();
	}

    job_finalize();

    history_finalize();
    builtin_finalize();

    return 0;
}
Пример #5
0
void test() {
  int multipnm=1;
  job_t job;


  while (multipnm==1) {
    job_init(&job);

    job.cfg.out_format=XML;
    job.cfg.cfilter = filter;
    job.src.fname = "patch00000.pgm";   // TODO

    multipnm=readpgm(job.src.fname, &job.src.p, job.cfg.verbose);
 
    if (multipnm<0) break; 

    pgm2asc(&job);

    int linecounter = 0;
  const char *line;
  line = getTextLine(linecounter++);
  while (line) {
    //fputs(line, stdout);
    //Interpret line here

    line = getTextLine(linecounter++);
  }
  free_textlines();
    job_free(&job);
  }
  return;
}
Пример #6
0
int cmus_init(void)
{
	playable_exts = ip_get_supported_extensions();
	cache_init();
	job_init();
	play_queue_init();
	return 0;
}
Пример #7
0
 void parallelOperation(double **a, double **b, double **c, int size, int operation)
 {
	int i;
	struct work_struct *jobs[CPUCORES];

	aa = a;
	bb = b;
	cc = c;

	matrixSize = size;

	for (i = 0; i < CPUCORES; i++) {
		jobs[i] = malloc(sizeof(struct work_struct));
		if (jobs[i] == NULL) {
			perror(NULL);
			exit(1);
		}
		jobs[i]->id = i;
	}
	
	job_init();
	
	switch(operation){
		case MULTIPLY:{
	//		printf("Multiply[%d]: ", size);
			for (i = 1; i < CPUCORES; i++)
				job_create(mm, jobs[i], 0);
			mm(jobs[0]);
		}break;

		case VECTOR:{
	//		printf("Vector[%d]: ", size);
			for (i = 1; i < CPUCORES; i++)
				job_create(mv, jobs[i], 0);
			mv(jobs[0]);
		}break;

		case ADD:{
	//		printf("Add[%d]: ", size);
			for (i = 1; i < CPUCORES; i++)
				job_create(add, jobs[i], 0);
			add(jobs[0]);
		}break;

		case SCALE:{
	//		printf("Scale[%d]: ", size);
			for (i = 1; i < CPUCORES; i++)
				job_create(scale, jobs[i], 0);
			scale(jobs[0]);
		}break;
	}
		

	for (i = 1; i < CPUCORES; i++)
		job_join(jobs[i]);

//	printf("\n");
}
Пример #8
0
int
database_load (struct database *wdb) {
  /* This function returns 1 on success and 0 on failure */
  /* It logs failure and maybe it should leave that task to the calling function */
  /* README : this function writes to the database without locking */
  struct database_hdr hdr;
  char *basedir;
  char filename[BUFFERLEN];
  int fd;
  int c;           /* counters */

  // FIXME: no filename guessing.
  if ((basedir = getenv ("DRQUEUE_DB")) == NULL) {
    /* This should never happen because we check it at the beginning of the program */
    drerrno = DRE_NOENVROOT;
    return 0;
  }

  snprintf (filename, BUFFERLEN - 1, "%s/drqueue.db", basedir);

  if ((fd = open (filename, O_RDONLY)) == -1) {
    drerrno = DRE_ERROROPENING;
    return 0;
  }

  read_32b (fd, &hdr.magic);
  if (hdr.magic != DB_MAGIC) {
    drerrno = DRE_DIFFILEFORMAT;
    close (fd);
    return 0;
  }
  read_32b (fd, &hdr.version);
  if (hdr.version != database_version_id()) {
    drerrno = DRE_DIFVERSION;
    close (fd);
    return 0;
  }
  read_16b (fd, &hdr.job_size);
  if (hdr.job_size != MAXJOBS) {
    drerrno = DRE_DIFJOBSIZE;
    close (fd);
    return 0;
  }

  for (c = 0; c < hdr.job_size; c++) {
    job_init(&wdb->job[c]);
    if (!database_job_load (fd, &wdb->job[c])) {
      log_auto (L_ERROR,"database_load(): error loading job number %i. (%s)",c,strerror(drerrno_system));
      close (fd);
      return 0;
    }
  }

  drerrno = DRE_NOERROR;
  close (fd);
  return 1;
}
Пример #9
0
int
main(int argc, char **argv)
{
    int r, l;
    struct event_base *ev_base;
    struct job binlog_jobs = {};

    progname = argv[0];
    opts(argc, argv);

    if (detach && binlog_dir) {
        if (binlog_dir[0] != '/') {
            warnx("The -b option requires an absolute path when used with -d.");
            usage("Path is not absolute", binlog_dir);
        }
    }

    job_init();
    prot_init();

    /* We want to make sure that only one beanstalkd tries to use the binlog
     * directory at a time. So acquire a lock now and never release it. */
    if (binlog_dir) {
        r = binlog_lock();
        if (!r) twarnx("failed to lock binlog dir %s", binlog_dir), exit(10);
    }

    r = make_server_socket(host_addr, port);
    if (r == -1) twarnx("make_server_socket()"), exit(111);
    l = r;

    if (user) su(user);
    ev_base = event_init();
    set_sig_handlers();
    nudge_fd_limit();

    r = listen(l, 1024);
    if (r == -1) twarn("listen()");
    accept_handler = (evh)h_accept;
    unbrake();

    binlog_jobs.prev = binlog_jobs.next = &binlog_jobs;
    binlog_init(&binlog_jobs);
    prot_replay_binlog(&binlog_jobs);

    if (detach) {
        daemonize();
        event_reinit(ev_base);
    }

    event_dispatch();
    twarnx("event_dispatch error");
    binlog_shutdown();
    return 0;
}
Пример #10
0
list_t * push_jobs(list_t * files, clinfo_t * clinfo
                   , Eina_Hash *map_histo)
{
    int code;
    list_t * job_waits = NULL;
    int count = 0;
    int histo_done = eina_hash_population(map_histo);
    int global = list_size(files);
    while(files != NULL) {
        char * filename = files->value;
        files = files->next;

        histogram_t *cached_elem = eina_hash_find(map_histo, filename);
        if(cached_elem)
            continue;

        image_t * image = image_init();
        image->path = filename;
        image = read_image(image);
        if (image == NULL) {
            continue;
        }
        if (image->size[0] > *clinfo->max_width
                || image->size[1] > *clinfo->max_heigth) {
            printf("Ignoring %s, width=%i, height=%i\n", filename
                   , image->size[0], image->size[1]);
            image_free(image);
            continue;
        }

        job_t * job = job_init();
        code = init_job_from_image(image, job);
        if(code == EXIT_FAILURE) {
            fprintf(stderr, "Could not init job from image %i\n"
                    , code);
            return NULL;
        }
        generate_histogram(clinfo, image, job);
        clFlush(clinfo->command_queue);
        count++;
        if ( count > 50 ) {
            histogram_t *histo = wait_and_fetch_histo_from_job(job);
            eina_hash_add(map_histo, strdup(histo->file), histo);
            histo_done++;
            count--;
            if(histo_done % 50 == 0) {
                printf("Processed %i / %i\n", histo_done, global);
                write_histogram_to_file(CACHE_FILE, map_histo);
            }
        } else {
            job_waits = list_append(job_waits, job);
        }
    }
    return job_waits;
}
Пример #11
0
static VALUE image_recognize(VALUE self, VALUE arg) {
    VALUE tmp;

    job_t job1, *job; /* fixme, dont want global variables for lib */
    job=OCR_JOB=&job1;
    job_init(job);
    
    job->src.fname = StringValuePtr(arg);
    tmp = rb_iv_get(self, "@database");
    if (tmp != Qnil) {
        job->cfg.db_path = StringValuePtr(tmp);
    }
    tmp = rb_iv_get(self, "@format");
    if (tmp != Qnil) {
        job->cfg.out_format = NUM2INT(tmp);
    }
    tmp = rb_iv_get(self, "@whitelist");
    if (tmp != Qnil) {
        if (strlen(StringValuePtr(tmp)) > 0)
            job->cfg.cfilter = StringValuePtr(tmp);
    }
    tmp = rb_iv_get(self, "@dust_size");
    if (tmp != Qnil) {
        job->cfg.dust_size = NUM2INT(tmp);
    }
    tmp = rb_iv_get(self, "@gray_level");
    if (tmp != Qnil) {
        job->cfg.cs = NUM2INT(tmp);
    }
    tmp = rb_iv_get(self, "@space_width");
    if (tmp != Qnil) {
        job->cfg.spc = NUM2INT(tmp);
    }
    tmp = rb_iv_get(self, "@mode");
    if (tmp != Qnil) {
        job->cfg.mode |= NUM2INT(tmp);
    }
    tmp = rb_iv_get(self, "@numbers_only");
    if (tmp == Qtrue) {
        job->cfg.only_numbers = 1;
    }
    tmp = rb_iv_get(self, "@certainty");
    if (tmp != Qnil) {
        job->cfg.certainty = NUM2INT(tmp);
    }
    tmp = rb_iv_get(self, "@unrecognize_char");
    if (tmp != Qnil) {
        job->cfg.unrec_marker = StringValuePtr(tmp)[0];
    }
    return rb_str_new2( gocr_main(job) );
}
Пример #12
0
void event_init()
{
  // Initialize the event queue
  event_queue = kl_init(Event);
  // Initialize input events
  input_init();
  // Timer to wake the event loop if a timeout argument is passed to
  // `event_poll`
  // Signals
  signal_init();
  // Jobs
  job_init();
  uv_timer_init(uv_default_loop(), &timer);
  // This prepare handle that actually starts the timer
  uv_prepare_init(uv_default_loop(), &timer_prepare);
}
Пример #13
0
void event_init()
{
  // Initialize the event queues
  deferred_events = kl_init(Event);
  immediate_events = kl_init(Event);
  // Initialize input events
  input_init();
  // Timer to wake the event loop if a timeout argument is passed to
  // `event_poll`
  // Signals
  signal_init();
  // Jobs
  job_init();
  // Channels
  channel_init();
  // Servers
  server_init();
}
Пример #14
0
/* -------------------------------------------------------------
// ------   MAIN - replace this by your own aplication! 
// ------------------------------------------------------------- */
int main(int argn, char *argv[]) {
  int multipnm=1;
  job_t job1, *job; /* fixme, dont want global variables for lib */
  job=OCR_JOB=&job1;

  setvbuf(stdout, (char *) NULL, _IONBF, 0);	/* not buffered */

  job_init(job); /* init cfg and db */

  process_arguments(job, argn, argv);
  
  /* load character data base (JS1002: now outside pgm2asc) */
  if ( job->cfg.mode & 2 ) /* check for db-option flag */
    load_db(job);
    /* load_db uses readpnm() and would conflict with multi images */
        
  while (multipnm==1) { /* multi-image loop */

    job_init_image(job); /* single image */

    mark_start(job);

    multipnm = read_picture(job);
    /* separation of main and rest for using as lib
       this will be changed later => introduction of set_option()
       for better communication to the engine  */
    if (multipnm<0) break; /* read error */
  
    /* call main loop */
    pgm2asc(job);

    mark_end(job);
  
    print_output(job);

    job_free_image(job);

  }

  return ((multipnm<0)?multipnm:0); /* -1=255 on error, 0 ok */
}
Пример #15
0
void event_init(void)
{
  // Initialize the event queues
  deferred_events = kl_init(Event);
  immediate_events = kl_init(Event);
  // early msgpack-rpc initialization
  msgpack_rpc_init_method_table();
  msgpack_rpc_helpers_init();
  // Initialize input events
  input_init();
  // Timer to wake the event loop if a timeout argument is passed to
  // `event_poll`
  // Signals
  signal_init();
  // Jobs
  job_init();
  // finish mspgack-rpc initialization
  channel_init();
  server_init();
  terminal_init();
}
Пример #16
0
ushort lcs(const struct sequence *s1, const struct sequence *s2)
{
	ushort alen = s1->len;
	ushort blen = s2->len;

	job_init();

	struct work_struct a_work = {
		.id   = 0,
		.a    = s1->str,
		.alen = alen,
		.b    = s2->str,
		.blen = blen,
		.ret  = NULL
	};

	struct work_struct b_work = {
		.id   = 1,
		.a    = s1->str,
		.alen = alen,
		.b    = s2->str,
		.blen = blen,
		.ret  = NULL
	};

	job_create(memo_lcs_front, &a_work, 0);
	memo_lcs_back(&b_work);
	job_join(&a_work);

	ushort *forward	= a_work.ret;
	ushort *backward = b_work.ret;

	ushort i = 0;
	ushort ibest = 0;
	for (i = 1; i < blen + 1; i++) {
		if (forward[i] + backward[i - 1] > ibest)
			ibest = forward[i] + backward[i - 1];
	}
	return ibest;
}
Пример #17
0
void
database_init (struct database *wdb) {
  uint32_t i;

  for (i = 0; i < MAXJOBS; i++) {
    envvars_init(&wdb->job[i].envvars); // First we set proper
                                        // defaults for the envvars to
                                        // avoid Warning messages
    job_init (&wdb->job[i]);
  }

  for (i = 0; i < MAXCOMPUTERS; i++) {
    computer_init (&wdb->computer[i]);
  }

#ifdef COMM_REPORT
  wdb->bsent = wdb->brecv = 0;
#endif

  wdb->lb.last_priority = 0;
  wdb->lb.next_i = 0;
}
Пример #18
0
void test_email_notify()
{
  scheduler_t* scheduler;
  job_t* job;
  int jq_pk;

  scheduler = scheduler_init(testdb, NULL);

  FO_ASSERT_PTR_NULL(scheduler->db_conn);
  database_init(scheduler);
  email_init(scheduler);
  FO_ASSERT_PTR_NOT_NULL(scheduler->db_conn);

  jq_pk = Prepare_Testing_Data(scheduler);
  job = job_init(scheduler->job_list, scheduler->job_queue, "ununpack", "localhost", -1, 0, 0, 0, 0, NULL);
  job->id = jq_pk;
 
  database_update_job(scheduler, job, JB_FAILED); 
  FO_ASSERT_STRING_EQUAL(job_status_strings[job->status], "JOB_CHECKEDOUT");

  scheduler_destroy(scheduler);
}
Пример #19
0
// Initialize and start PSL thread
//
// The return value is encode int a 16-bit value divided into 4 for each
// possible adapter.  Then the 4 bits in each adapter represent the 4 possible
// AFUs on an adapter.  For example: afu0.0 is 0x8000 and afu3.0 is 0x0008.
uint16_t psl_init(struct psl **head, struct parms *parms, char *id, char *host,
		  int port, pthread_mutex_t * lock, FILE * dbg_fp)
{
	struct psl *psl;
	struct job_event *reset;
	uint16_t location;

	location = 0x8000;
	if ((psl = (struct psl *)calloc(1, sizeof(struct psl))) == NULL) {
		perror("malloc");
		error_msg("Unable to allocation memory for psl");
		goto init_fail;
	}
	psl->timeout = parms->timeout;
	if ((strlen(id) != 6) || strncmp(id, "afu", 3) || (id[4] != '.')) {
		warn_msg("Invalid afu name: %s", id);
		goto init_fail;
	}
	if ((id[3] < '0') || (id[3] > '3')) {
		warn_msg("Invalid afu major: %c", id[3]);
		goto init_fail;
	}
	if ((id[5] < '0') || (id[5] > '3')) {
		warn_msg("Invalid afu minor: %c", id[5]);
		goto init_fail;
	}
	psl->dbg_fp = dbg_fp;
	psl->major = id[3] - '0';
	psl->minor = id[5] - '0';
	psl->dbg_id = psl->major << 4;
	psl->dbg_id |= psl->minor;
	location >>= (4 * psl->major);
	location >>= psl->minor;
	if ((psl->name = (char *)malloc(strlen(id) + 1)) == NULL) {
		perror("malloc");
		error_msg("Unable to allocation memory for psl->name");
		goto init_fail;
	}
	strcpy(psl->name, id);
	if ((psl->host = (char *)malloc(strlen(host) + 1)) == NULL) {
		perror("malloc");
		error_msg("Unable to allocation memory for psl->host");
		goto init_fail;
	}
	strcpy(psl->host, host);
	psl->port = port;
	psl->client = NULL;
	psl->idle_cycles = PSL_IDLE_CYCLES;
	psl->lock = lock;

	// Connect to AFU
	psl->afu_event = (struct AFU_EVENT *)malloc(sizeof(struct AFU_EVENT));
	if (psl->afu_event == NULL) {
		perror("malloc");
		goto init_fail;
	}
	info_msg("Attempting to connect AFU: %s @ %s:%d", psl->name,
		 psl->host, psl->port);
	if (psl_init_afu_event(psl->afu_event, psl->host, psl->port) !=
	    PSL_SUCCESS) {
		warn_msg("Unable to connect AFU: %s @ %s:%d", psl->name,
			 psl->host, psl->port);
		goto init_fail;
	}
	// DEBUG
	debug_afu_connect(psl->dbg_fp, psl->dbg_id);

	// Initialize job handler
	if ((psl->job = job_init(psl->afu_event, &(psl->state), psl->name,
				 psl->dbg_fp, psl->dbg_id)) == NULL) {
		perror("job_init");
		goto init_fail;
	}
	// Initialize mmio handler
	if ((psl->mmio = mmio_init(psl->afu_event, psl->timeout, psl->name,
				   psl->dbg_fp, psl->dbg_id)) == NULL) {
		perror("mmio_init");
		goto init_fail;
	}
	// Initialize cmd handler
	if ((psl->cmd = cmd_init(psl->afu_event, parms, psl->mmio,
				 &(psl->state), psl->name, psl->dbg_fp,
				 psl->dbg_id))
	    == NULL) {
		perror("cmd_init");
		goto init_fail;
	}
	// Set credits for AFU
	if (psl_aux1_change(psl->afu_event, psl->cmd->credits) != PSL_SUCCESS) {
		warn_msg("Unable to set credits");
		goto init_fail;
	}
	// Start psl loop thread
	if (pthread_create(&(psl->thread), NULL, _psl_loop, psl)) {
		perror("pthread_create");
		goto init_fail;
	}
	// Add psl to list
	while ((*head != NULL) && ((*head)->major < psl->major)) {
		head = &((*head)->_next);
	}
	while ((*head != NULL) && ((*head)->major == psl->major) &&
	       ((*head)->minor < psl->minor)) {
		head = &((*head)->_next);
	}
	psl->_next = *head;
	if (psl->_next != NULL)
		psl->_next->_prev = psl;
	*head = psl;

	// Send reset to AFU
	reset = add_job(psl->job, PSL_JOB_RESET, 0L);
	while (psl->job->job == reset) {	/*infinite loop */
		lock_delay(psl->lock);
	}

	// Read AFU descriptor
	psl->state = PSLSE_DESC;
	read_descriptor(psl->mmio, psl->lock);

	// Finish PSL configuration
	psl->state = PSLSE_IDLE;
	if (dedicated_mode_support(psl->mmio)) {
		// AFU supports Dedicated Mode
		psl->max_clients = 1;
	}
	if (directed_mode_support(psl->mmio)) {
		// AFU supports Directed Mode
		psl->max_clients = psl->mmio->desc.num_of_processes;
	}
	if (psl->max_clients == 0) {
		error_msg("AFU programming model is invalid");
		goto init_fail;
	}
	psl->client = (struct client **)calloc(psl->max_clients,
					       sizeof(struct client *));
	psl->cmd->client = psl->client;
	psl->cmd->max_clients = psl->max_clients;

	return location;

 init_fail:
	if (psl) {
		if (psl->afu_event) {
			psl_close_afu_event(psl->afu_event);
			free(psl->afu_event);
		}
		if (psl->host)
			free(psl->host);
		if (psl->name)
			free(psl->name);
		free(psl);
	}
	pthread_mutex_unlock(lock);
	return 0;
}
Пример #20
0
int main(int argc, char *argv[])
{
    int ret, keeppidfile = 1;

    setlocale(LC_ALL, "");
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);

    lyxml_init();
    lyauth_init();

    /* start initializeing g_c */
    CLCConfig *c = malloc(sizeof(CLCConfig));
    if (c == NULL) {
        printf(_("malloc for g_c have a error.\n"));
        return -255;
    }
    g_c = c;

    /* parse command line option and configuration file */
    ret = clc_config(argc, argv, c);
    if (ret == CLC_CONFIG_RET_HELP)
        usage();
    else if (ret == CLC_CONFIG_RET_VER)
        printf(_("%s : Version %s\n"), PROGRAM_NAME, PROGRAM_VERSION);
    else if (ret == CLC_CONFIG_RET_ERR_CMD)
        printf(_
               ("command line parsing error, use -h option to display usage\n"));
    else if (ret == CLC_CONFIG_RET_ERR_NOCONF) {
        printf(_
               ("missing lyclc config file, default build-in settings are used.\n"));
        ret = 0;
    }
    else if (ret == CLC_CONFIG_RET_ERR_ERRCONF)
        printf(_("can not find %s.\n"), c->conf_path);
    else if (ret == CLC_CONFIG_RET_ERR_CONF)
        printf(_("reading config file %s returned error\n"), c->conf_path);
    else if (ret == CLC_CONFIG_RET_ERR_UNKNOWN)
        printf(_("internal error\n"));

    /* exit if ret is not zero */
    if (ret != 0)
        goto out;

    /* node cpu/mem factors */
    if (c->node_cpu_factor == 0)
        c->node_cpu_factor = DEFAULT_NODE_CPU_FACTOR;
    if (c->node_mem_factor == 0)
        c->node_mem_factor = DEFAULT_NODE_MEM_FACTOR;

    /* for debuuging */
    if (c->debug)
        __print_config(c);

    /* make sure data directory exists */
    if (lyutil_create_dir(c->clc_data_dir)) {
        printf(_("%s is not accessible\n"), c->clc_data_dir);
        ret = -255;
        goto out;
    }

    /* check whether program is started already */
    ret = lyutil_check_pid_file(c->pid_path, PROGRAM_NAME);
    if (ret == 1) {
        printf(_("%s is running already.\n"), PROGRAM_NAME);
        goto out;
    }
    else if (ret != 0) {
        printf(_("error checking pid file.\n"));
        goto out;
    }

    /* check DB */
    if (ly_db_check() < 0) {
        printf(_("failed connecting DB\n"));
        ret = -255;
        goto out;
    }

    /* get clc ip */
    if (c->clc_ip == NULL && ly_clc_ip_get() < 0) {
        logerror(_("CLC no proper network interface to use.\n"));
        goto out;
    }

    /* Daemonize the progress */
    if (c->daemon) {
        if (c->debug == LYDEBUG)
            printf(_("Run as daemon, log to %s.\n"), c->log_path);
        lyutil_daemonize(__main_clean, keeppidfile);
        logfile(c->log_path, c->debug ? LYDEBUG : c->verbose ? LYINFO : LYWARN);
    }
    else
        logfile(NULL, c->debug ? LYDEBUG : c->verbose ? LYINFO : LYWARN);

    /* create lock file */
    ret = lyutil_create_pid_file(c->pid_path, PROGRAM_NAME);
    if (ret == 1) {
        logsimple(_("%s is running already.\n"), PROGRAM_NAME);
        ret = 0;
        goto out;
    }
    else if (ret != 0) {
        logsimple(_("error creating pid file.\n"));
        goto out;
    }
    keeppidfile = 0;

    /* init db connection */
    if (ly_db_init() < 0) {
        logsimple(_("ly_db_init failed.\n"));
        ret = -255;
        goto out;
    }

    /* initialize entity store */
    if (ly_entity_store_init() < 0) {
        logsimple(_("ly_entity_init failed.\n"));
        ret = -255;
        goto out;
    }

    /* init job queue */
    if (job_init() < 0 || job_internal_init() < 0) {
        logsimple(_("job_init failed.\n"));
        ret = -255;
        goto out;
    }
    if (c->debug)
        job_print_queue();

    /* set up signal handler */
    lyutil_signal_init();

    /* handle specific signal */
    struct sigaction sa;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = __sig_handler;
    if (sigaction(SIGTERM, &sa, NULL)) {
        logsimple(_("Setting signal handler error.\n"));
        ret = -255;
        goto out;
    }

    /* initialize g_c->efd */
    if (ly_epoll_init(EPOLL_EVENTS_MAX) != 0) {
        logsimple(_("ly_epoll_init failed.\n"));
        ret = -255;
        goto out;
    }

    if (ly_epoll_work_start(g_c->clc_port) != 0) {
        ret = -1;
        logsimple(_("ly_epoll_init failed.\n"));
        goto out;
    }

    /* init timeout values */
    time_t mcast_join_time, job_dispatch_time, job_internal_time;
    mcast_join_time = 0;
    time(&job_dispatch_time);
    job_internal_time = job_dispatch_time + (CLC_MCAST_JOIN_INTERVAL<<1);
    job_dispatch_time = job_dispatch_time + (CLC_MCAST_JOIN_INTERVAL<<2);

    /* start main event driven loop */
    if (c->clc_ip)
        loginfo(_("clc uses IP %s\n"), c->clc_ip);
    else
        loginfo(_("clc uses IP automatically detected\n"));
    loginfo(_("start event loop, waiting for events ...\n"));
    int i, n = 0;
    struct epoll_event events[EPOLL_EVENTS_MAX];
    while (1) {
        time_t time_now;
        time(&time_now);

        /* send mcast request */
        if (time_now - mcast_join_time > CLC_MCAST_JOIN_INTERVAL) {
            if (ly_mcast_send_join() < 0)
                logerror(_("failed sending mcast request.\n"));
            mcast_join_time = time_now;
        }
        else if (time_now < mcast_join_time)
            mcast_join_time = time_now;

        /* job dispatch */
        if (time_now - job_dispatch_time > CLC_JOB_DISPATCH_INTERVAL) {
            if (job_dispatch() < 0)
                logerror(_("job_dispatch failed.\n"));
            job_dispatch_time = time_now;
        }
        else if (time_now < job_dispatch_time)
            job_dispatch_time = time_now;

        /* internal job dispatch */
        if (time_now - job_internal_time > CLC_JOB_INTERNAL_INTERVAL) {
            if (job_internal_dispatch() < 0)
                logerror(_("job_internal failed.\n"));
            job_internal_time = time_now;
        }
        else if (time_now < job_internal_time)
            job_internal_time = time_now;

        n = epoll_wait(g_efd, events, EPOLL_EVENTS_MAX,
                       CLC_EPOLL_TIMEOUT);
        if (n != 0)
            logdebug(_("waiting ... got %d events\n"), n);
        for (i = 0; i < n; i++) {
            int id = events[i].data.fd;
            if (events[i].events & EPOLLIN) {
                ret = ly_epoll_entity_recv(id);
                if (ret < 0) {
                    logerror(_("epoll_data_recv error\n"));
                }
                else if (ret > 0) {
                    loginfo(_("release entity %d\n"), id);
                    ly_entity_release(id);
                }
            }
            else if (events[i].events & EPOLLRDHUP) {
                loginfo(_("epoll entity(%d) got rdhup. close.\n"), id);
                ly_entity_release(id);
            }
            else if (events[i].events & EPOLLHUP) {
                loginfo(_("epoll entity(%d) got hup. close.\n"), id);
                ly_entity_release(id);
            }
            else {
                logerror(_("unexpected event(%d, %d). ignore.\n"),
                         events[i].events, id);
            }
        }
    }

out:
    __main_clean(keeppidfile);
    if (ret <= 0)
        loginfo(_("%s exits\n"), PROGRAM_NAME);
    return ret;
}
Пример #21
0
void request_run(request *r, suq_serv *cs)
{
    int i;
    int arg_ind;
    int cont=1;
    char *wd=r->wd;
    job *j=malloc_check_server(sizeof(job));
    char *arg;

    job_init(j);

    j->id=suq_settings_get_next_id(cs->st);

    j->buf=malloc_check_server(r->buflen+1);
    /* just copy the whole buffer. This buffer will contain all
        variables that the job's cmd, argv[] etc. point to. */
    memcpy(j->buf, r->buf, r->buflen);

    arg_ind=2; /* the starting index to check */

    j->ntask=1;
    /* process arguments first */
    do
    {
        arg=request_get_arg(r, arg_ind);
        if (!arg) goto err;

        if (strcmp(arg, "-d") == 0)
        {
            wd=request_get_arg(r, ++arg_ind);
            if (!wd) goto err;
            ++arg_ind;
        }
        else if (strcmp(arg, "-n") == 0)
        {
            char *nps;
            char *end;
            int ntask;

            nps=request_get_arg(r, ++arg_ind);
            if (!nps) goto err;
            ntask=strtol(nps, &end, 10);
            if (end==nps || ntask<1)
            {
                request_reply_errstring(r, "suq run -n is not a number > 1");
                goto err;
            }
            /* we don't unset a blocking attribute */
            if (j->ntask>=1)
                j->ntask=ntask;
            ++arg_ind;
        }
        else if (strcmp(arg, "-p") == 0)
        {
            char *nps;
            char *end;

            nps=request_get_arg(r, ++arg_ind);
            if (!nps) goto err;
            j->prio=strtol(nps, &end, 10);
            if (end==nps)
            {
                request_reply_errstring(r, "suq run -p is not a number");
                goto err;
            }
            ++arg_ind;
        }
        else if (strcmp(arg, "-b")==0)
        {
            j->ntask=-1;
            ++arg_ind;
        }
        else
            cont=0;
    } while(cont);



    /* then make all the pointers */
    j->argc=r->argc-arg_ind;
    j->envc=r->envc;
    j->argv=malloc_check_server(sizeof(char*)*(j->argc+1));
    j->envp=malloc_check_server(sizeof(char*)*(j->envc+1));

    j->wd = j->buf + (wd - r->buf);
    arg=request_get_arg(r, arg_ind);
    if (!arg) goto err;
    j->cmd = j->buf + (arg - r->buf);

    /* the argvs */
    for(i=arg_ind;i<r->argc;i++)
    {
        arg=request_get_arg(r, i);
        if (!arg) goto err;
        j->argv[i-arg_ind] = j->buf + (arg - r->buf);
    }
    j->argv[j->argc]=NULL;

    /* the envps */
    for(i=0;i<j->envc;i++)
    {
        j->envp[i] = j->buf + (r->envp[i] - r->buf);
    }
    j->envp[j->envc]=NULL;

    /* now construct everything from this data */
    job_reinit(j);

    /* then process the job */
    j->state=waiting;

    joblist_add(&(cs->jl), j);
    joblist_check_run(&(cs->jl), cs);

    /* print result */
    request_reply_printf(r, "Submitted job id %d: '%s'. ", j->id, j->name);

    if (j->state == running)
        request_reply_printf(r,"Job is running.\n");
    else if (j->state == waiting)
        request_reply_printf(r,"Job is waiting to run.\n");
    else if (j->state == resource_error || j->state == run_error)
        request_reply_printf(r,"\nJob ERROR: '%s'.\n", j->error_string);

    if (debug>1)
    {
        printf("SERVER: new job id=%d, ntask=%d, name=%s, cmd=%s", 
               j->id, j->ntask, j->name, j->cmd);
        printf(", argc=%d, envc=%d, wd=%s\n", j->argc, j->envc, j->wd);
    }

    return;
err:
    if (j->buf)
        free(j->buf);
    if (j->argv)
        free(j->argv);
    free(j);
}
Пример #22
0
char get_atom_label(const Magick::Image &image, const Magick::ColorGray &bg, int x1, int y1, int x2, int y2,
                    double THRESHOLD, int dropx, int dropy, bool no_filtering, bool verbose, bool numbers)
{
  char c = UNKNOWN_CHAR;

  const int width = x2 - x1 + 1;
  const int height = y2 - y1 + 1;

  unsigned char *pixmap = (unsigned char *) malloc(width * height);

  for (int i = y1; i <= y2; i++)
    for (int j = x1; j <= x2; j++)
      pixmap[(i - y1) * width + j - x1] = (unsigned char) (255 - 255 * get_pixel(image, bg, j, i, THRESHOLD));

  // Here we drop down from the top of the box, middle of x coordinate and extract connected component
  int t = 1;
  int y = dropy - y1 + 1;
  int x = dropx - x1;

  while ((t != 0) && (y < height))
    {
      t = pixmap[y * width + x];
      y++;
    }

  if (t != 0)
    {
      free(pixmap);
      return 0;
    }

  #pragma omp critical
  {
    y--;

    pixmap[y * width + x] = 2;

    list<int> cx;
    list<int> cy;

    cx.push_back(x);
    cy.push_back(y);

    while (!cx.empty())
      {
        x = cx.front();
        y = cy.front();
        cx.pop_front();
        cy.pop_front();
        pixmap[y * width + x] = 1;

        // this goes around 3x3 square touching the chosen pixel
        for (int i = x - 1; i < x + 2; i++)
          for (int j = y - 1; j < y + 2; j++)
            if (i < width && j < height && i >= 0 && j >= 0 && pixmap[j * width + i] == 0)
              {
                cx.push_back(i);
                cy.push_back(j);
                pixmap[j * width + i] = 2;
              }
      }

    // Flatten the bitmap. Note: the bitmap is inverted after this cycle (255 means "empty", 0 means "pixel").
    for (int i = 0; i < height; i++)
      for (int j = 0; j < width; j++)
        pixmap[i * width + j] = (pixmap[i * width + j] == 1 ? 0 : 255);

    job_t gocr_job;

    // The list of all characters, that can be recognised as atom label:
    string char_filter = RECOGNIZED_CHARS;
    if (numbers) char_filter = "1";
    if (no_filtering) char_filter.clear();

    job_init(&gocr_job);
    job_init_image(&gocr_job);

    //gocr_job.cfg.cs = 160;
    //gocr_job.cfg.certainty = 80;
    //gocr_job.cfg.dust_size = 1;
    gocr_job.src.p.x = width;
    gocr_job.src.p.y = height;
    gocr_job.src.p.bpp = 1;
    gocr_job.src.p.p = pixmap;
    if (char_filter.empty())
      gocr_job.cfg.cfilter = (char*)NULL;
    else
      gocr_job.cfg.cfilter = (char*) char_filter.c_str();

    struct OCRAD_Pixmap *ocrad_pixmap = new OCRAD_Pixmap();
    unsigned char *ocrad_bitmap = (unsigned char *) malloc(width * height);

    memset(ocrad_bitmap, 0, width * height);

    ocrad_pixmap->height = height;
    ocrad_pixmap->width = width;
    ocrad_pixmap->mode = OCRAD_bitmap;
    ocrad_pixmap->data = ocrad_bitmap;

    // Number of non-zero pixels on the bitmap, excluding the 1px border:
    int pixmap_pixels_count = 0;
    // Number of zero pixels on the bitmap, excluding the 1px border:
    int pixmap_zeros_count = 0;

    // The code below initialises "opix->data" buffer ("bitmap_data") for OCRAD from "tmp" buffer:
#ifdef HAVE_CUNEIFORM_LIB
    Magick::Image cuneiform_img(Magick::Geometry(2 * width + 2, height), "white");
    // From cuneiform_src/cli/cuneiform-cli.cpp::preprocess_image(Magick::Image&):168
    cuneiform_img.monochrome();
    cuneiform_img.type(Magick::BilevelType);
#endif
    for (int y = 0; y < height; y++)
      {
        for (int x = 0; x < width; x++)
          {
            if (pixmap[y * width + x] == 0)
              {
                ocrad_bitmap[y * width + x] = 1;
#ifdef HAVE_CUNEIFORM_LIB
                // Draw two identical samples that follow one another. We do so because Cuneiform has difficulties in recognizing single characters:
                cuneiform_img.pixelColor(x, y, "black");
                cuneiform_img.pixelColor(x + width + 2, y, "black");
#endif
                if (x > 0 && x < width - 1 && y > 0 && y < height - 1)
                  pixmap_pixels_count++;
              }
            else if (x > 0 && x < width - 1 && y > 0 && y < height - 1)
              pixmap_zeros_count++;
          }
      }

    if (verbose)
      {
        cout << "Box to OCR: " << x1 << "x" << y1 << "-" << x2 << "x" << y2 << " w/h: " << width << "x" << height << endl;
        for (int i = 0; i < height; i++)
          {
            for (int j = 0; j < width; j++)
              cout << (gocr_job.src.p.p[i * width + j] / 255 ? '#' : '.');
            cout << endl;
          }
      }

    if (pixmap_pixels_count <= MIN_CHAR_POINTS || pixmap_zeros_count <= MIN_CHAR_POINTS)
      goto FINALIZE;

    c = osra_gocr_ocr(gocr_job);

    if (verbose)
      cout << "GOCR: c=" << c << endl;

    //c = UNKNOWN_CHAR; // Switch off GOCR recognition

    // Character recognition succeeded for GOCR:
    if (c != UNKNOWN_CHAR)
      goto FINALIZE;

    // Character recognition failed for GOCR and we try OCRAD:
    c = osra_ocrad_ocr(ocrad_pixmap, char_filter);

    if (verbose)
      cout << "OCRAD: c=" << c << endl;

    //c = UNKNOWN_CHAR;  // Switch off OCRAD recognition

    // Character recognition succeeded for OCRAD:
    if (c != UNKNOWN_CHAR)
      goto FINALIZE;

#ifdef HAVE_TESSERACT_LIB
    c = osra_tesseract_ocr(gocr_job.src.p.p, width, height, char_filter);

    if (verbose)
      cout << "Tesseract: c=" << c << endl;

    //c = UNKNOWN_CHAR;  // Switch off Tesseract recognition

    // Character recognition succeeded for Tesseract:
    if (c != UNKNOWN_CHAR)
      goto FINALIZE;
#endif
#ifdef HAVE_CUNEIFORM_LIB
    // TODO: Why box width should be more than 7 for Cuneiform?
    if (width <= 7)
      goto FINALIZE;

    c = osra_cuneiform_ocr(cuneiform_img, char_filter);

    if (verbose)
      cout << "Cuneiform: c=" << c << endl;

    //c = UNKNOWN_CHAR; // Switch off Cuneiform recognition
#endif

FINALIZE:
    // "pixmap" is freed together with "gocr_job".
    job_free_image(&gocr_job);
    OCR_JOB = NULL;
    JOB = NULL;

    delete ocrad_pixmap; // delete OCRAD Pixmap
    free(ocrad_bitmap);

    // TODO: Why there are problems with "7" with a given box size? If the problem is engine-specific, it should be moved to appropriate section
    if (c == '7' && (width <= 10 || height <= 20))
      c = UNKNOWN_CHAR;
  } // #pragma omp critical

  return(c == UNKNOWN_CHAR ? 0 : c);
}
Пример #23
0
void strassen_8thread_mult(matrix a, matrix b, matrix c){
	matrix quar[12];
	matrix m[7];
	struct work_struct *jobs[7];
	int size = a.size/2;
	int i, j;
	
	if(size==0){
		c.rows[0][0] = a.rows[0][0] * b.rows[0][0];
		return;
	}

	/*
	if (a.size <= BREAK) {
		int i, j, k;
		for (i = 0; i < (a.size); i++) {
			for (k = 0; k < (a.size); k++) {
				for (j = 0; j < (a.size); j++) {
					c.rows[i][j] += a.rows[i][k] * b.rows[k][j];
				}
			}
		}
        return;
    }
	*/
	
	job_init();
	
	quar[0]=get00(a);  quar[1]=get01(a);
	quar[2]=get10(a);  quar[3]=get11(a);

	quar[4]=get00(b);  quar[5]=get01(b);
	quar[6]=get10(b);  quar[7]=get11(b);

	quar[8]=get00(c);  quar[9]=get01(c);
	quar[10]=get10(c); quar[11]=get11(c);

	for(i=0;i<7;i++){
		m[i] = new_matrix(size);
	}

	for (i = 0; i < 7; i++) {
		jobs[i] = malloc(sizeof(struct work_struct));
		if (jobs[i] == NULL) {
			perror(NULL);
			exit(1);
		}
	}
	
	jobs[0]->a_1 = quar[0];
	jobs[0]->a_2 = quar[3];
	jobs[0]->b_1 = quar[4];
	jobs[0]->b_2 = quar[7];
	jobs[0]->c = m[0];
	jobs[0]->tid = 0;
	job_create(thread_main, jobs[0], 0);


	jobs[1]->a_1 = quar[2];
	jobs[1]->a_2 = quar[3];
	jobs[1]->b_1 = quar[4];
	jobs[1]->c = m[1];
	jobs[1]->tid = 1;
	job_create(thread_main, jobs[1], 0);


	jobs[2]->a_1 = quar[0];
	jobs[2]->b_1 = quar[5];
	jobs[2]->b_2 = quar[7];
	jobs[2]->c = m[2];
	jobs[2]->tid = 2;
	job_create(thread_main, jobs[2], 0);


	jobs[3]->a_1 = quar[3];
	jobs[3]->b_1 = quar[6];
	jobs[3]->b_2 = quar[4];
	jobs[3]->c = m[3];
	jobs[3]->tid = 3;
	job_create(thread_main, jobs[3], 0);


	jobs[4]->a_1 = quar[0];
	jobs[4]->a_2 = quar[1];
	jobs[4]->b_1 = quar[7];
	jobs[4]->c = m[4];
	jobs[4]->tid = 4;
	job_create(thread_main, jobs[4], 0);


	jobs[5]->a_1 = quar[2];
	jobs[5]->a_2 = quar[0];
	jobs[5]->b_1 = quar[4];
	jobs[5]->b_2 = quar[5];
	jobs[5]->c = m[5];
	jobs[5]->tid = 5;
	job_create(thread_main, jobs[5], 0);


	jobs[6]->a_1 = quar[1];
	jobs[6]->a_2 = quar[3];
	jobs[6]->b_1 = quar[6];
	jobs[6]->b_2 = quar[7];
	jobs[6]->c = m[6];
	jobs[6]->tid = 6;
	job_create(thread_main, jobs[6], 0);


	for(i=0;i<7;i++){
		job_join(jobs[i]);
	}

	for(i=0;i<size;i++){
		for(j=0;j<size;j++){
			quar[8].rows[i][j] = m[0].rows[i][j] + m[3].rows[i][j] - m[4].rows[i][j] + m[6].rows[i][j];
			quar[9].rows[i][j] = m[2].rows[i][j] + m[4].rows[i][j];
			quar[10].rows[i][j] = m[1].rows[i][j] + m[3].rows[i][j];
			quar[11].rows[i][j] = m[0].rows[i][j] - m[1].rows[i][j] + m[2].rows[i][j] + m[5].rows[i][j];
		}
	}

	for(i=0;i<12;i++){
		delete_matrix(quar[i]);
	}
	for(i=0;i<7;i++){
		delete_matrix(m[i]);
	}
}
Пример #24
0
int sh_main(int ac, char *av[], Shinit_f userinit)
{
	register char	*name;
	register int	fdin;
	register Sfio_t  *iop;
	register Shell_t *shp;
	struct stat	statb;
	int i, rshflag;		/* set for restricted shell */
	char *command;
	free(malloc(64*1024));
#ifdef _lib_sigvec
	/* This is to clear mask that may be left on by rlogin */
	clearsigmask(SIGALRM);
	clearsigmask(SIGHUP);
	clearsigmask(SIGCHLD);
#endif /* _lib_sigvec */
#ifdef	_hdr_nc
	_NutConf(_NC_SET_SUFFIXED_SEARCHING, 1);
#endif	/* _hdr_nc */
	fixargs(av,0);
	shp = sh_init(ac,av,userinit);
	time(&mailtime);
	if(rshflag=sh_isoption(SH_RESTRICTED))
		sh_offoption(SH_RESTRICTED);
	if(sigsetjmp(*((sigjmp_buf*)shp->jmpbuffer),0))
	{
		/* begin script execution here */
		sh_reinit((char**)0);
		shp->gd->pid = getpid();
		shp->gd->ppid = getppid();
	}
	shp->fn_depth = shp->dot_depth = 0;
	command = error_info.id;
	/* set pidname '$$' */
	srand(shp->gd->pid&0x7fff);
	if(nv_isnull(PS4NOD))
		nv_putval(PS4NOD,e_traceprompt,NV_RDONLY);
	path_pwd(shp,1);
	iop = (Sfio_t*)0;
#if SHOPT_BRACEPAT
	sh_onoption(SH_BRACEEXPAND);
#endif
	if((beenhere++)==0)
	{
		sh_onstate(SH_PROFILE);
		((Lex_t*)shp->lex_context)->nonstandard = 0;
		if(shp->gd->ppid==1)
			shp->login_sh++;
		if(shp->login_sh >= 2)
			sh_onoption(SH_LOGIN_SHELL);
		/* decide whether shell is interactive */
		if(!sh_isoption(SH_INTERACTIVE) && !sh_isoption(SH_TFLAG) && !sh_isoption(SH_CFLAG) &&
		   sh_isoption(SH_SFLAG) && tty_check(0) && tty_check(ERRIO))
			sh_onoption(SH_INTERACTIVE);
		if(sh_isoption(SH_INTERACTIVE))
		{
			sh_onoption(SH_BGNICE);
			sh_onoption(SH_RC);
		}
		if(!sh_isoption(SH_RC) && (sh_isoption(SH_BASH) && !sh_isoption(SH_POSIX)
#if SHOPT_REMOTE
		   || !fstat(0, &statb) && REMOTE(statb.st_mode)
#endif
		  ))
			sh_onoption(SH_RC);
		for(i=0; i<elementsof(shp->offoptions.v); i++)
			shp->options.v[i] &= ~shp->offoptions.v[i];
		if(sh_isoption(SH_INTERACTIVE))
		{
#ifdef SIGXCPU
			signal(SIGXCPU,SIG_DFL);
#endif /* SIGXCPU */
#ifdef SIGXFSZ
			signal(SIGXFSZ,SIG_DFL);
#endif /* SIGXFSZ */
			sh_onoption(SH_MONITOR);
		}
		job_init(shp,sh_isoption(SH_LOGIN_SHELL));
		if(sh_isoption(SH_LOGIN_SHELL))
		{
			/*	system profile	*/
			sh_source(shp, iop, e_sysprofile);
			if(!sh_isoption(SH_NOUSRPROFILE) && !sh_isoption(SH_PRIVILEGED))
			{
				char **files = shp->gd->login_files;
				while ((name = *files++) && !sh_source(shp, iop, sh_mactry(shp,name)));
			}
		}
		/* make sure PWD is set up correctly */
		path_pwd(shp,1);
		if(!sh_isoption(SH_NOEXEC))
		{
			if(!sh_isoption(SH_NOUSRPROFILE) && !sh_isoption(SH_PRIVILEGED) && sh_isoption(SH_RC))
			{
#if SHOPT_BASH
				if(sh_isoption(SH_BASH) && !sh_isoption(SH_POSIX))
				{
#if SHOPT_SYSRC
					sh_source(shp, iop, e_bash_sysrc);
#endif
					sh_source(shp, iop, shp->gd->rcfile ? shp->gd->rcfile : sh_mactry(shp,(char*)e_bash_rc));
				}
				else
#endif
				{
					if(name = sh_mactry(shp,nv_getval(ENVNOD)))
						name = *name ? strdup(name) : (char*)0;
#if SHOPT_SYSRC
					if(!strmatch(name, "?(.)/./*"))
						sh_source(shp, iop, e_sysrc);
#endif
					if(name)
					{
						sh_source(shp, iop, name);
						free(name);
					}
				}
			}
			else if(sh_isoption(SH_INTERACTIVE) && sh_isoption(SH_PRIVILEGED))
				sh_source(shp, iop, e_suidprofile);
		}
		shp->st.cmdname = error_info.id = command;
		sh_offstate(SH_PROFILE);
		if(rshflag)
			sh_onoption(SH_RESTRICTED);
		/* open input file if specified */
		if(shp->comdiv)
		{
		shell_c:
			iop = sfnew(NIL(Sfio_t*),shp->comdiv,strlen(shp->comdiv),0,SF_STRING|SF_READ);
		}
Пример #25
0
int main(int argc, char **argv) {
     time_t now;

     /* Initialise route, runq and job classes */
     now = time(NULL);
     route_init(NULL, 0);
     route_register(&rt_filea_method);
     route_register(&rt_fileov_method);
     route_register(&rt_stdin_method);
     route_register(&rt_stdout_method);
     route_register(&rt_stderr_method);
     if ( ! elog_init(1, "job test", NULL))
	  elog_die(FATAL, "didn't initialise elog\n");
     sig_init();
     callback_init();
     runq_init(now);
     meth_init();
     job_init();

     /* Test should fail due to incorrect method */
     elog_printf(DEBUG, "Expect a complaint! -> ");
     if (job_add(5, 5, 0, 1, "test1a1", "internal_test", "stdout", 
		  "stderr", 100, NULL, "echo \"Hello, world\"") != -1)
     {
	  elog_die(FATAL, "[1a] Shouldn't be able to add\n");
     }

     /* Single test in five seconds, never to run */
     if (job_add(5, 5, 0, 1, "test1a2", "internal_test", "stdout", 
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1a] Can't add\n");
     }
				/* Attention: some white box testing */
     itree_first(runq_event);
     if (itree_getkey(runq_event) != now+5) {
	  elog_die(FATAL, "[1a] Queued at an incorrect time\n");
     }
     job_clear();
     if (!itree_empty(runq_event) || !itree_empty(runq_tab)) {
	  elog_die(FATAL, 
		  "[1a] Trees not emptied. runq_events=%d, runq_tab=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab));
     }
     now = time(NULL);
     
     /* Two tests both in five seconds, never to run */
     if (job_add(5, 5, 0, 1, "test1b1", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1b] Can't add first\n");
     }
     if (job_add(5, 5, 0, 1, "test1b2", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1b] Can't add second\n");
     }
     itree_first(runq_event);
     if (itree_getkey(runq_event) != now+5) {
	  elog_die(FATAL, "[1b] First queued at an incorrect time\n");
     }
     itree_next(runq_event);
     if (itree_getkey(runq_event) != now+5) {
	  elog_die(FATAL, "[1b] Second queued at an incorrect time\n");
     }
     job_clear();
     if (!itree_empty(runq_event) || !itree_empty(runq_tab)) {
	  elog_die(FATAL, 
		  "[1b] Trees not emptied. runq_events=%d, runq_tab=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab));
     }
     now = time(NULL);

     /* Two tests one in five seconds, the other in six, never to run */
     if (job_add(6, 6, 0, 1, "test1c1", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1c] Can't add first\n");
     }
     if (job_add(now+5, 5, 0, 1, "test1c2", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1c] Can't add second\n");
     }
     itree_first(runq_event);
     if (itree_getkey(runq_event) != now+5) {
	  elog_die(FATAL, "[1c] First queued at an incorrect time\n");
     }
     itree_next(runq_event);
     if (itree_getkey(runq_event) != now+6) {
	  elog_die(FATAL, "[1c] Second queued at an incorrect time\n");
     }
     job_clear();
     if (!itree_empty(runq_event) || !itree_empty(runq_tab)) {
	  elog_die(FATAL, 
		  "[1c] Trees not emptied. runq_events=%d, runq_tab=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab));
     }
     now = time(NULL);
     
     /* Continuous single test supposed to start two seconds ago, 
      * next run in three; never to run */
     if (job_add(-2, 5, 0, 0, "test1d1", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1d] Can't add\n");
     }
     itree_first(runq_event);
     if (itree_getkey(runq_event) != now+3) {
	  elog_die(FATAL, 
		  "[1d] Event queued at an incorrect time: bad=%d good=%ld\n", 
		  itree_getkey(runq_event), now+3);
     }
     job_clear();
     if (runq_nsched() > 0) {
	  elog_die(FATAL, "[1d] Still active work scheduled. runq_events=%d, "
		  "runq_tab=%d runq_nsched()=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab), runq_nsched());
	  runq_dump();
     }
     now = time(NULL);
     
     /* Two continous tests, starting two seconds ago, next next run in four;
      * never to run */
     if (job_add(-2, 6, 0, 0, "test1e1", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1e] Can't add first\n");
     }
     if (job_add(-3, 5, 0, 0, "test1e2", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1e] Can't add second\n");
     }
     itree_first(runq_event);
     while (((struct runq_work*) itree_get(runq_event))->expired)
	  itree_next(runq_event);
     if (itree_getkey(runq_event) != now+2) {
	  elog_die(FATAL, "[1e] First queued at an incorrect time\n");
     }
     itree_next(runq_event);
     while (((struct runq_work*) itree_get(runq_event))->expired)
	  itree_next(runq_event);
     if (itree_getkey(runq_event) != now+4) {
	  elog_die(FATAL, "[1e] Second queued at an incorrect time\n");
     }
     job_clear();
     if (runq_nsched() > 0) {
	  elog_die(FATAL, "[1e] Still active work scheduled. runq_events=%d, "
		  "runq_tab=%d runq_nsched()=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab), runq_nsched());
	  runq_dump();
     }
     now = time(NULL);
     
     /* Two 5 run jobs, scheduled to start 10 seconds ago, with periods
      * of 5 and 6 seconds; never to run */
     if (job_add(-10, 6, 0, 5, "test1f1", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1f] Can't add first\n");
     }
     if (job_add(-10, 5, 0, 5, "test1f2", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1f] Can't add second\n");
     }

     itree_first(runq_event);
     while (((struct runq_work*) itree_get(runq_event))->expired)
	  itree_next(runq_event);
     if (itree_getkey(runq_event) != now+2) {
	  elog_die(FATAL, "[1f] First queued at an incorrect time\n");
     }
     itree_next(runq_event);
     while (((struct runq_work*) itree_get(runq_event))->expired)
	  itree_next(runq_event);
     if (itree_getkey(runq_event) != now+5) {
	  elog_die(FATAL, "[1f] Second queued at an incorrect time\n");
     }
     job_clear();
     if (runq_nsched() > 0) {
	  elog_die(FATAL, "[1f] Still active work scheduled. runq_events=%d, "
		  "runq_tab=%d runq_nsched()=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab), runq_nsched());
	  runq_dump();
     }
     now = time(NULL);
     
     /* Two 5 run jobs, scheduled to start 100 seconds ago, with periods
      * of 5 and 6 seconds; they should never be scheduled */
     if (job_add(-100, 6, 0, 5, "test1g1", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1g] Can't add first\n");
     }
     if (job_add(-100, 5, 0, 5, "test1g2", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1g] Can't add second\n");
     }
     if (runq_nsched() > 0) {
	  elog_die(FATAL, "[1g] Still active work scheduled. runq_events=%d, "
		  "runq_tab=%d runq_nsched()=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab), runq_nsched());
	  runq_dump();
     }
     job_clear();
     now = time(NULL);

     /* Two five run tests, starting at different times in the past,
      * five runs each wittth different periods; they should both
      * run now */
     if (job_add(-24, 6, 0, 5, "test1h1", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1h] Can't add first\n");
     }
     if (job_add(-20, 5, 0, 5, "test1h2", "internal_test", "stdout",
		  "stderr", 100, "exec", "echo \"Hello, world\"") == -1)
     {
	  elog_die(FATAL, "[1h] Can't add second\n");
     }
     if (runq_nsched() != 2) {
	  elog_die(FATAL, "[1h] Two jobs should be scheduled not %d\n",
		  runq_nsched());
	  runq_dump();
     }
     sig_on();
     sleep(6);		/* let it run */
     sleep(1);		/* let it run */
     sleep(1);		/* let it run */
     sleep(1);		/* let it run */
     sig_off();
     if (runq_nsched() > 0) {
	  elog_die(FATAL, "[1h] Still active work scheduled. runq_events=%d, "
		  "runq_tab=%d runq_nsched()=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab), runq_nsched());
	  runq_dump();
     }

     job_clear();

#if 0
     /* check all tables/lists are empty */
     if (!itree_empty(runq_event) || !itree_empty(runq_tab)) {
	  elog_die(FATAL, "[1i] Still entries in tables. runq_events=%d, "
		  "runq_tab=%d runq_nsched()=%d\n", 
		  itree_n(runq_event), itree_n(runq_tab), runq_nsched());
	  runq_dump();
     }
#endif

     job_fini();
     meth_fini();
     runq_fini();
     elog_fini();
     route_fini();
     callback_fini();

     printf("%s: tests finished\n", argv[0]);
     exit(0);
}