Example #1
0
static void fb_switch_shutdown(void)
{
	int rs;
	if (in_gr_operation <= 0) internal("fb_switch_shutdown: in_gr_operation %d", in_gr_operation);
	if (!fb_active && in_gr_operation == 1) {
		EINTRLOOP(rs, ioctl(TTY,VT_RELDISP,1));
	}
	EINTRLOOP(rs, ioctl(TTY,VT_SETMODE, &vt_omode));
	install_signal_handler(SIG_REL, (void (*)(void *))NULL, (void*)SIG_REL, 1);
	install_signal_handler(SIG_ACQ, (void (*)(void *))NULL, (void*)SIG_ACQ, 0);
	in_gr_operation--;
}
Example #2
0
void
handle_basic_signals(struct terminal *term)
{
return;
#ifdef SIGHUP
	install_signal_handler(SIGHUP, (void (*)(void *)) sig_intr, term, 0);
#endif
	install_signal_handler(SIGINT, (void (*)(void *)) sig_ctrl_c, term, 0);
	install_signal_handler(SIGTERM, (void (*)(void *)) sig_terminate, term, 0);
#ifdef SIGTSTP
	install_signal_handler(SIGTSTP, (void (*)(void *)) sig_tstp, term, 0);
#endif
#ifdef SIGTTIN
	install_signal_handler(SIGTTIN, (void (*)(void *)) sig_tstp, term, 0);
#endif
#ifdef SIGTTOU
	install_signal_handler(SIGTTOU, (void (*)(void *)) sig_ign, term, 0);
#endif
#ifdef SIGCONT
	install_signal_handler(SIGCONT, (void (*)(void *)) sig_cont, term, 0);
#endif
#ifdef CONFIG_BACKTRACE
	install_signal_handler(SIGSEGV, (void (*)(void *)) sig_segv, term, 1);
#endif
}
Example #3
0
void
set_sigcld(void)
{
#ifdef SIGCHLD
    install_signal_handler(SIGCHLD, sig_chld, NULL, 1);
#endif
}
Example #4
0
int main(int argc, char **argv) {
  int ret_val;
  struct utsname uinfo;

  uname(&uinfo);
  if (uinfo.release[0] == '2' && uinfo.release[2] == '6')
    maxDepth = 1;
  
  p_saved_ctxt = malloc(sizeof(ucontext_t));

  setup_signal_stack();
  install_signal_handler();

  ret_val = getcontext(p_saved_ctxt);
  if(ret_val) {
    perror("ERROR, getcontext failed");
    exit(1);
  }

  p_saved_ctxt->uc_mcontext.gregs[REG_EIP] = (int)&&safe_exit;

  generate_segv(1);

 safe_exit:  
  printf("safe exit\n");
  printSignalMask();

  return 0;
}
Example #5
0
static void fb_shutdown_driver(void)
{
	int rs;
	mem_free(mouse_buffer);
	mem_free(background_buffer);
	mem_free(new_background_buffer);
	fb_driver.shutdown_device(mouse_graphics_device);
	unhandle_fb_mouse();
	INC_IN_GR
	if (fb_active) {
		fb_clear_videoram();
		/*EINTRLOOP(rs, ioctl(fb_handle, FBIOPUT_VSCREENINFO, &oldmode));*/
	}
	fb_shutdown_palette();
	EINTRLOOP(rs, close(fb_handle));
	EINTRLOOP(rs, munmap(fb_mem,fb_mapped_size));
	shutdown_virtual_devices();
	fb_switch_shutdown();
	svgalib_free_trm(fb_kbd);
	if(fb_driver_param) mem_free(fb_driver_param);
	/* show cursor */
	fb_show_cursor();
	install_signal_handler(SIGINT, (void (*)(void *))NULL, NULL, 0);

	if (in_gr_operation) internal("fb_shutdown_driver: in_gr_operation %d", in_gr_operation);
}
Example #6
0
int main(int argc, char* argv[])
{
	parse_argv(argc, argv);

	printf("listen address:     %s:%d\n", inet_ntoa(server_address.sin_addr),
		ntohs(server_address.sin_port));
	printf("broadcast address   %s:%d\n", inet_ntoa(bcast_address.sin_addr),
		ntohs(bcast_address.sin_port));
	printf("tftp address:       %s\n", inet_ntoa(tftp_ip));
	printf("nbp name:           %s\n", nbp_name);

	/* install signal handler */
	if (install_signal_handler() == -1) {
		perror("sigaction() failed");
		exit(-1);
	}

	/* init sockets */
	if (init_socket() == -1) {
		perror("init_socket()");
		release_all();
		exit(1);
	}

	if (foreground) {
		pdhcp();
	} else {
		daemon(0,0);
		pdhcp();
	}

	return 0;
}
Example #7
0
void handle_basic_signals( struct terminal *term )
{
  install_signal_handler( 1, &sig_intr, (void*)term, 0 );
  install_signal_handler( 2, &sig_ctrl_c, (void*)term, 0 );
  install_signal_handler( 15, &sig_terminate, (void*)term, 0 );
  install_signal_handler( 20, &sig_tstp, (void*)term, 0 );
  install_signal_handler( 21, &sig_tstp, (void*)term, 0 );
  install_signal_handler( 22, &sig_ign, (void*)term, 0 );
  install_signal_handler( 18, &sig_cont, (void*)term, 0 );
  install_signal_handler( 11, &sig_segv, (void*)term, 1 );
  return;
}
Example #8
0
int main (int argc, char *argv[]) {
  char *filename = NULL;
     
  install_signal_handler(); 
  parse_argv(argc, argv, &filename);

  run(filename);

  return EXIT_SUCCESS;
}
Example #9
0
void unhandle_basic_signals( struct terminal *term )
{
  install_signal_handler( 1, 0, 0, 0 );
  install_signal_handler( 2, 0, 0, 0 );
  install_signal_handler( 15, 0, 0, 0 );
  install_signal_handler( 20, 0, 0, 0 );
  install_signal_handler( 21, 0, 0, 0 );
  install_signal_handler( 22, 0, 0, 0 );
  install_signal_handler( 18, 0, 0, 0 );
  install_signal_handler( 11, 0, 0, 0 );
  return;
}
Example #10
0
int main(int argc, char *argv[]){
  int t_wait;

  install_signal_handler(); /* Instala el manejador de CTRL + C */
  
  parse_argv(argc,argv,&t_wait); /* Controla la linea de argumentos                                  */
  run(t_wait); /* Ejecuta el programa */

  return EXIT_SUCCESS;
}
int main (int argc, char *argv[]) {
  char *line = NULL, *pattern = NULL;
  int line_number;
     
  install_signal_handler(); 
  parse_argv(argc, argv, &line, &line_number, &pattern);

  run(line, line_number, pattern);

  return EXIT_SUCCESS;
}
Example #12
0
void check_for_select_race( void )
{
  if ( critical_section )
  {
    install_signal_handler( 14, &alarm_handler, 0, 1 );
    pending_alarm = 1;
    alarm( 1 );
    return;
  }
  return;
}
Example #13
0
void rbkit_install_sampling_profiler(int wall_time, int interval, queue_sample_func_ptr func) {
  queue_cpu_sample_for_sending = func;
  if(wall_time) {
    signal_type = SIGALRM;
    clock_type = ITIMER_REAL;
  } else {
    signal_type = SIGPROF;
    clock_type = ITIMER_PROF;
  }
  install_signal_handler();
  start_sigprof_timer(interval);
}
Example #14
0
static unsigned char *fb_switch_init(void)
{
	int rs;

	INC_IN_GR

	/* If we use threads, the signal handler may execute on a different
	   thread. framebuf.c doesn't handle different-thread signals, so
	   we must switch to synchronous signal handling when using threads */
	install_signal_handler(SIG_REL, fb_switch_signal_rel, NULL,
#ifndef EXEC_IN_THREADS
		1
#else
		0
#endif
		);
	install_signal_handler(SIG_ACQ, fb_switch_signal_acq, NULL, 0);
	EINTRLOOP(rs, ioctl(TTY,VT_GETMODE, &vt_omode));
	if (rs == -1) {
		in_gr_operation--;
		return stracpy(cast_uchar "Could not get VT mode.\n");
	}
	memcpy(&vt_mode, &vt_omode, sizeof(vt_mode));

	vt_mode.mode   = VT_PROCESS;
	vt_mode.waitv  = 0;
	vt_mode.relsig = SIG_REL;
	vt_mode.acqsig = SIG_ACQ;

	EINTRLOOP(rs, ioctl(TTY,VT_SETMODE, &vt_mode));
	if (rs == -1) {
		in_gr_operation--;
		return stracpy(cast_uchar "Could not set VT mode.\n");
	}

	EINTRLOOP(rs, ioctl(TTY, VT_WAITACTIVE, fb_console));
	fb_active = 1;

	return NULL;
}
Example #15
0
static void unhandle_fb_mouse(void)
{
	if (fb_hgpm >= 0) set_handlers(fb_hgpm, (void (*)(void *))NULL, (void (*)(void *))NULL, (void (*)(void *))NULL, NULL);
#ifndef USE_GPM_DX
	fb_hgpm = -1;
	if (fb_old_ws_v) {
		int rs;
		EINTRLOOP(rs, ioctl(1, TIOCSWINSZ, &fb_old_ws));
		fb_old_ws_v = 0;
	}
#endif
	Gpm_Close();
#ifdef SIGTSTP
	install_signal_handler(SIGTSTP, (void (*)(void *))sig_tstp, NULL, 0);
#endif
#ifdef SIGCONT
	install_signal_handler(SIGCONT, (void (*)(void *))sig_cont, NULL, 0);
#endif
#ifdef SIGTTIN
	install_signal_handler(SIGTTIN, (void (*)(void *))sig_tstp, NULL, 0);
#endif
}
Example #16
0
static void
check_for_select_race(void)
{
    if (critical_section) {
#ifdef SIGALRM
        install_signal_handler(SIGALRM, alarm_handler, NULL, 1);
#endif
        pending_alarm = 1;
#ifdef HAVE_ALARM
        alarm(1);
#endif
    }
}
Example #17
0
void install_signal_handlers_server()
{
	install_signal_handler(SIGCHLD, signal_handler_server);
	install_signal_handler(SIGTERM, signal_handler_server);
	install_signal_handler(SIGINT, signal_handler_server);
	install_signal_handler(SIGALRM, signal_handler_server);
	install_signal_handler(SIGPIPE, signal_handler_server);
	install_signal_handler(SIGHUP, signal_handler_server);
}
Example #18
0
int main(int argc, char **argv) {
  pthread_t tid;
  int ret_val;
  void *thread_ret;
  int cont = 0;

  setup_signal_stack();
  install_signal_handler();

  ret_val = pthread_create(&tid, NULL, thread_start, NULL);
  if(ret_val) {
    perror("ERROR, pthread_create failed");
    exit(1);
  }

  printf("created thread 0x%lx\n", (long)tid);

  while(!cont) {
    lock();
    if(thread_alive == 1) cont = 1;
    unlock();
  }

  ret_val = pthread_kill(tid, SIGUSR1);
  if(ret_val) {
    perror("ERROR: pthread_kill failed");
    exit(1);
  }

  cont = 0;
  while(!cont) {
    lock();
    if(thread_alive == 2) cont = 1;
    unlock();
  }

  ret_val = pthread_kill(tid, SIGUSR1);
  if(ret_val) {
    perror("ERROR: pthread_kill failed");
    exit(1);
  }

  ret_val = pthread_join(tid, NULL);
  if(ret_val) {
    perror("ERROR: pthread_join failed");
    exit(1);
  }
}
int main(int argc, char *argv[]) {
  char *filename = NULL, *pattern = NULL;
  int lines = 0,n_Proc;

  parse_argv(argc, argv, &filename, &pattern, &lines,&n_Proc);
  install_signal_handler();

  init_process_table(&n_Proc,lines);
  create_processes(lines, n_Proc, filename, pattern);
  wait_processes();

  printf("\n[MANAGER] Program termination (all the processes terminated).\n");
  free_resources();

  return EXIT_SUCCESS;
}
int main(int argc,char *argv[]){
  char *TimeMAX_wait = NULL;
  int nPA,nPB;

  parse_argv(argc,argv,&nPA,&nPB,&TimeMAX_wait);
  install_signal_handler();

  init_TProc(nPA,nPB);

  create_proc_byclass(PB,nPB,0,TimeMAX_wait);
  create_proc_byclass(PA,nPA,nPB,TimeMAX_wait);

  wait_proc(nPA);

  printf("[MANAGER] Program Termination (all PA processes terminated)\n");
  termProc();
  freeResources();

  return EXIT_SUCCESS;
}
Example #21
0
static void
unhandle_basic_signals(struct terminal *term)
{
#ifdef SIGHUP
    install_signal_handler(SIGHUP, NULL, NULL, 0);
#endif
    install_signal_handler(SIGINT, NULL, NULL, 0);
    install_signal_handler(SIGTERM, NULL, NULL, 0);
#ifdef SIGTSTP
    install_signal_handler(SIGTSTP, NULL, NULL, 0);
#endif
#ifdef SIGTTIN
    install_signal_handler(SIGTTIN, NULL, NULL, 0);
#endif
#ifdef SIGTTOU
    install_signal_handler(SIGTTOU, NULL, NULL, 0);
#endif
#ifdef SIGCONT
    install_signal_handler(SIGCONT, NULL, NULL, 0);
#endif
#ifdef CONFIG_BACKTRACE
    install_signal_handler(SIGSEGV, NULL, NULL, 0);
#endif
}
Example #22
0
static void handle_basic_signals(struct terminal *term)
{
	install_signal_handler(SIGHUP, (void (*)(void *))sig_intr, term, 0);
	if (!F) install_signal_handler(SIGINT, (void (*)(void *))sig_ctrl_c, term, 0);
	/*install_signal_handler(SIGTERM, (void (*)(void *))sig_terminate, term, 0);*/
#ifdef WIN32
	install_signal_handler(SIGQUIT, (void (*)(void *))sig_terminate, term, 0);
#endif
#ifdef SIGTSTP
	if (!F) install_signal_handler(SIGTSTP, (void (*)(void *))sig_tstp, term, 0);
#endif
#ifdef SIGTTIN
	if (!F) install_signal_handler(SIGTTIN, (void (*)(void *))sig_tstp, term, 0);
#endif
#ifdef SIGTTOU
	install_signal_handler(SIGTTOU, (void (*)(void *))sig_ign, term, 0);
#endif
#ifdef SIGCONT
	if (!F) install_signal_handler(SIGCONT, (void (*)(void *))sig_cont, term, 0);
#endif
}
Example #23
0
File: main.c Project: ebichu/dd-wrt
void unhandle_terminal_signals(struct terminal *term)
{
	install_signal_handler(SIGHUP, NULL, NULL, 0);
	install_signal_handler(SIGINT, NULL, NULL, 0);
#ifdef SIGTSTP
	install_signal_handler(SIGTSTP, NULL, NULL, 0);
#endif
#ifdef SIGTTIN
	install_signal_handler(SIGTTIN, NULL, NULL, 0);
#endif
#ifdef SIGTTOU
	install_signal_handler(SIGTTOU, NULL, NULL, 0);
#endif
#ifdef SIGCONT
	install_signal_handler(SIGCONT, NULL, NULL, 0);
#endif
	if (fg_poll_timer != -1) kill_timer(fg_poll_timer), fg_poll_timer = -1;
}
Example #24
0
gboolean
signal_set_handler (int          signo,
		    SignalFunc   handler,
		    gpointer     data,
		    GError     **err)
{
    SignalWatch *watch;
    
    g_return_val_if_fail (lookup_signal_watch (signo) == NULL, FALSE);

    if (read_end == -1)
    {
        if (!create_pipe (&read_end, &write_end, err))
            return FALSE;

        fd_add_watch (read_end, NULL);
        fd_set_read_callback (read_end, on_read);
    }
    
    watch = g_new0 (SignalWatch, 1);
    
    watch->signo = signo;
    watch->handler = handler;
    watch->user_data = data;
    watch->next = signal_watches;
    signal_watches = watch;
    
    if (!install_signal_handler (signo, &watch->old_action, err))
    {
        signal_watch_free (watch);
        
        return FALSE;
    }
        
    return TRUE;
}
Example #25
0
int main(int argc, char **argv)
{
    CSOUND  *csound;
    char    *fname = NULL;
    int     i, result, nomessages=0;
#ifdef GNU_GETTEXT
    const char* lang;
#endif
    install_signal_handler();
    csoundInitialize(CSOUNDINIT_NO_SIGNAL_HANDLER);

    /* set stdout to non buffering if not outputing to console window */
    if (!isatty(fileno(stdout))) {
#if !defined(WIN32)
      setvbuf(stdout, (char*) NULL, _IONBF, 0);
#endif
    }

#ifdef GNU_GETTEXT
    /* We need to set the locale for the translations to work */
    lang = csoundGetEnv(NULL, "CS_LANG");
    /* If set, use that. Otherwise use the system locale */
    if(lang == NULL)
        lang = setlocale(LC_MESSAGES, "");
    else
        lang = setlocale(LC_MESSAGES, lang);
    /* Should we warn if we couldn't set the locale (lang == NULL)? */
    /* If the strings for this binary are ever translated,
     * the textdomain should be set here */
#endif

    /* Real-time scheduling on Linux by Istvan Varga (Jan 6 2002) */
#ifdef LINUX
    if (set_rt_priority(argc, argv) != 0)
      return -1;

#endif
    /* open log file if specified */
    for (i = 1; i < argc; i++) {
      if (strncmp(argv[i], "-O", 2) == 0 && (int) strlen(argv[i]) > 2)
        fname = argv[i] + 2;
      else if (strncmp(argv[i], "--logfile=", 10) == 0 &&
               (int) strlen(argv[i]) > 10)
        fname = argv[i] + 10;
      else if (i < (argc - 1) && strcmp(argv[i], "-O") == 0)
        fname = argv[i + 1];
    }
    if (fname != NULL) {
      if (!strcmp(fname, "NULL") || !strcmp(fname, "null"))
               nomessages = 1;
      else if ((logFile = fopen(fname, "w")) == NULL) {
        fprintf(stderr, "Error opening log file '%s': %s\n",
                        fname, strerror(errno));
        return -1;
      }
    }
    /* if logging to file, set message callback */
    if (logFile != NULL)
      csoundSetDefaultMessageCallback(msg_callback);
    else if (nomessages)
      csoundSetDefaultMessageCallback(nomsg_callback);

    /*  Create Csound. */
    csound = csoundCreate(NULL);
    _csound = csound;

    /*  One complete performance cycle. */
    result = csoundCompile(csound, argc, argv);

     if(!result) csoundPerform(csound);

    /* delete Csound instance */
     csoundDestroy(csound);
     _csound = NULL;
    /* close log file */
    if (logFile != NULL)
      fclose(logFile);

    if(result == 0 && _result != 0) result = _result;
    // printf("csound returned with value: %d \n", result);
#if 0
    /* remove global configuration variables, if there are any */
    csoundDeleteAllGlobalConfigurationVariables();
#endif
    return (result >= 0 ? 0 : result);
}
Example #26
0
/**
 * main replayer method
 */
static void start(int option, int argc, char* argv[], char** envp)
{
	pid_t pid;
	int status, fake_argc;

	if (option == RECORD) {
		copy_executable(argv[2]);
		if (access(__executable, X_OK)) {
			printf("The specified file '%s' does not exist or is not executable\n", __executable);
			return;
		}

		/* create directory for trace files */
		setup_trace_dir(0);

		/* initialize trace files */
		open_trace_files();
		init_trace_files();
		copy_argv(argc, argv);
		copy_envp(envp);
		record_argv_envp(argc, __argv, __envp);
		close_trace_files();

		pid = sys_fork();
		/* child process */
		if (pid == 0) {
			sys_start_trace(__executable, __argv, __envp);
			/* parent process */
		} else {
			child = pid;

			/* make sure that the child process dies when the master process gets interrupted */
			install_signal_handler();

			/* sync with the child process */
			sys_waitpid(pid, &status);

			/* configure the child process to get a message upon a thread start, fork(), etc. */
			sys_ptrace_setup(pid);

			/* initialize stuff */
			init_libpfm();
			/* initialize the trace file here -- we need to record argc and envp */
			open_trace_files();

			/* register thread at the scheduler and start the HPC */
			rec_sched_register_thread(0, pid);

			/* perform the action recording */
			fprintf(stderr, "start recording...\n");
			start_recording();
			fprintf(stderr, "done recording -- cleaning up\n");
			/* cleanup all initialized data-structures */
			close_trace_files();
			close_libpfm();
		}

		/* replayer code comes here */
	} else if (option == REPLAY) {
		init_environment(argv[2], &fake_argc, __argv, __envp);

		copy_executable(__argv[0]);
		if (access(__executable, X_OK)) {
			printf("The specified file '%s' does not exist or is not executable\n", __executable);
			return;
		}

		pid = sys_fork();
		//child process
		if (pid == 0) {
			sys_start_trace(__executable, __argv, __envp);
			/* parent process */
		} else {
			child = pid;
			/* make sure that the child process dies when the master process gets interrupted */
			install_signal_handler();

			sys_waitpid(pid, &status);
			sys_ptrace_setup(pid);


			/* initialize stuff */
			init_libpfm();
			rep_sched_init();
			/* sets the file pointer to the first trace entry */

			read_trace_init(argv[2]);

			pid_t rec_main_thread = get_recorded_main_thread();
			rep_sched_register_thread(pid, rec_main_thread);

			/* main loop */
			replay();
			/* thread wants to exit*/
			close_libpfm();
			read_trace_close();
			rep_sched_close();
		}
	}
}
Example #27
0
 * Actual signal handler.
 */
#ifdef __VS
__declspec(noreturn) static void handle_signal(int signal) {
#else
[[noreturn]] static void handle_signal(int signal) {
#endif
	//printStacktrace(false);
	std::cerr << std::endl << "Catched SIGABRT " << signal << ", exiting with " << (last_assertion_code%256) << std::endl;
	if (!last_assertion_string.empty()) {
		std::cerr << "Last Assertion catched is: " << last_assertion_string << std::endl;
		std::cerr << "Please check if this is the assertion that is actually thrown." << std::endl;
	}
	exit(last_assertion_code % 256);
}
/**
 * Installs the signal handler.
 */
static bool install_signal_handler() noexcept {
	CARL_LOG_INFO("carl.util", "Installing signal handler for SIGABRT");
	std::signal(SIGABRT, handle_signal);
	return true;
}
/**
 * Static variable that ensures that install_signal_handler is called.
 */
static bool signal_installed = install_signal_handler();
#endif

}
Example #28
0
int evaluate_subset(CorpusList *cl, /* the corpus */
                    FieldType the_field,       /* the field to scan */
                    Constrainttree constr)
{
  int line, position;
  int percentage, new_percentage; /* for ProgressBar */

  assert(cl && constr);
  assert(cl->type == SUB || cl->type == TEMP);

  percentage = -1;

  EvaluationIsRunning = 1;
  for (line = 0; (line < cl->size) && EvaluationIsRunning; line++) {

    if (progress_bar) {
      new_percentage = floor(0.5 + (100.0 * line) / cl->size);
      if (new_percentage > percentage) {
        percentage = new_percentage;
        progress_bar_percentage(0, 0, percentage);
      }
    }

    switch (the_field) {
    
    case MatchField:
      position = cl->range[line].start;
      break;
      
    case MatchEndField:
      position = cl->range[line].end;
      break;
      
    case KeywordField:
      assert(cl->keywords);
      position = cl->keywords[line];
      break;
      
    case TargetField:
      assert(cl->targets);
      position = cl->targets[line];
      break;
      
    case NoField:
    default:
      position = -1;
      break;
    }

    if (position < 0 || (!eval_bool(constr, NULL, position))) {
      cl->range[line].start = -1;
      cl->range[line].end   = -1;
    }
  }
  
  /* if interrupted, delete part of temporary query result which hasn't been filtered;
     so that the result is incomplete but at least contains only correct matches */
  while (line < cl->size) {
    cl->range[line].start = -1;
    cl->range[line].end   = -1;
    line++;
  }

  if (!EvaluationIsRunning) {
    cqpmessage(Warning, "Evaluation interruted: results may be incomplete.");
    if (which_app == cqp) install_signal_handler();
  }
  EvaluationIsRunning = 0;

  if (progress_bar) 
    progress_bar_message(0, 0, "  cleaning up");

  (void) RangeSetop(cl, RReduce, NULL, NULL);

  return 1;
}
Example #29
0
int evaluate_target(CorpusList *corp,          /* the corpus */
                    FieldType t_id,            /* the field to set */
                    FieldType base,            /* where to start the search */
                    int inclusive,             /* including or excluding the base */
                    SearchStrategy strategy,   /* disambiguation rule: which item */
                    Constrainttree constr,     /* the constraint */
                    enum ctxtdir direction,    /* context direction */
                    int units,                       /* number of units */
                    char *attr_name)           /* name of unit */
{
  Attribute *attr;
  int *table;
  Context context;
  int i, line, lbound, rbound;
  int excl_start, excl_end;
  int nr_evals;
  int percentage, new_percentage; /* for ProgressBar */

  /* ------------------------------------------------------------ */

  assert(corp);

  /* consistency check */
  assert(t_id == TargetField || t_id == KeywordField || t_id == MatchField || t_id == MatchEndField);

  if (!constr) {
    cqpmessage(Error, "Constraing pattern missing in 'set target' command.");
    return 0;
  }

  if (corp->size <= 0) {
    cqpmessage(Error, "Corpus is empty.");
    return 0;
  }

  /*
   * check whether the base field specification is ok
   */
  switch(base) {
  case MatchField:
  case MatchEndField:
    if (corp->range == NULL) {
      cqpmessage(Error, "No ranges for start of search");
      return 0;
    }
    break;
  case TargetField:
    if (corp->targets == NULL) {
      cqpmessage(Error, "Can't start from base TARGET, none defined");
      return 0;
    }
    break;
  case KeywordField:
    if (corp->keywords == NULL) {
      cqpmessage(Error, "Can't start from base KEYWORD, none defined");
      return 0;
    }
    break;
  default:
    cqpmessage(Error, "Illegal base field (#%d) in 'set target' command.",
               base);
    return 0;
  }

  if (units <= 0) {
    cqpmessage(Error, "Invalid search space (%d units) in 'set target' command.", 
               units);
    return 0;
  }

  /* THIS SHOULD BE UNNECESSARY, BECAUSE THE GRAMMAR MAKES SURE THE SUBCORPUS EXISTS & IS LOADED */
  /*   if (!access_corpus(corp)) { */
  /*     cqpmessage(Error, "Can't access named query %s.", corp->name); */
  /*     return 0; */
  /*   } */

  context.size = units;
  context.direction = direction;

  if ((strcasecmp(attr_name, "word") == 0) ||
      (strcasecmp(attr_name, "words") == 0)) {
    attr = find_attribute(corp->corpus, DEFAULT_ATT_NAME, ATT_POS, NULL);
    context.type = word;
    context.attrib = NULL;
  }
  else {
    attr = find_attribute(corp->corpus, attr_name, ATT_STRUC, NULL);
    context.type = structure;
    context.attrib = attr;
  }

  if (attr == NULL) {
    cqpmessage(Error, "Can't find attribute %s.%s",
               corp->mother_name, attr_name);
    return 0;
  }

  if (progress_bar) {
    progress_bar_clear_line();
    progress_bar_message(1, 1, "    preparing");
  }


  table = (int *)cl_calloc(corp->size, sizeof(int));

  EvaluationIsRunning = 1;
  nr_evals = 0;
  percentage = -1;

  for (line = 0; line < corp->size && EvaluationIsRunning; line++) {

    if (progress_bar) {
      new_percentage = floor(0.5 + (100.0 * line) / corp->size);
      if (new_percentage > percentage) {
        percentage = new_percentage;
        progress_bar_percentage(0, 0, percentage);
      }
    }

    table[line] = -1;

    switch(base) {
    case MatchField:

      excl_start = corp->range[line].start;
      excl_end   = corp->range[line].end;

      if ((corp->range[line].start == corp->range[line].end) || inclusive) {

        if (calculate_ranges(corp,
                             corp->range[line].start, context,
                             &lbound, &rbound) == False) {

          Rprintf( "Can't compute boundaries for range #%d", line);
          lbound = rbound = -1;
        }
      }
      else {

        int dummy;

        if (calculate_ranges(corp,
                             corp->range[line].start, context,
                             &lbound, &dummy) == False) {

          Rprintf( "Can't compute left search space boundary match #%d", line);
          lbound = rbound = -1;
        }
        else if (calculate_ranges(corp,
                                  corp->range[line].end, context,
                                  &dummy, &rbound) == False) {

          Rprintf( "Can't compute right search space boundary match #%d", line);
          lbound = rbound = -1;
        }
      }
      break;

    case MatchEndField:
      excl_start = excl_end = corp->range[line].end;

      if (excl_start >= 0) {
        if (calculate_ranges(corp,
                             corp->range[line].end, context,
                             &lbound, &rbound) == False) {

          Rprintf( "Can't compute search space boundaries for match #%d", line);
          lbound = rbound = -1;
        }
      }
      else 
        lbound = rbound = -1;

      break;

    case TargetField:
      excl_start = excl_end = corp->targets[line];

      if (excl_start >= 0) {
        if (calculate_ranges(corp,
                             corp->targets[line], context,
                                  &lbound, &rbound) == False) {

          Rprintf( "Can't compute search space boundaries for match #%d", line);
          lbound = rbound = -1;
        }
      }
      else 
        lbound = rbound = -1;

      break;

    case KeywordField:
      excl_start = excl_end = corp->keywords[line];

      if (excl_start >= 0) {
        if (calculate_ranges(corp,
                             corp->keywords[line], context,
                             &lbound, &rbound) == False) {

          Rprintf( "Can't compute search space boundaries for match #%d", line);
          lbound = rbound = -1;
        }
      }
      else 
        lbound = rbound = -1;

      break;
    default:
      assert(0 && "Can't be");
      return 0;
    }

    if ((lbound >= 0) && (rbound >= 0)) {
      
      int dist, maxdist;

      if (direction == left) {
        rbound = excl_start;
        if (strategy == SearchNearest)
          strategy = SearchRightmost;
        else if (strategy == SearchFarthest)
          strategy = SearchLeftmost;
      }
      else if (direction == right) {
        lbound = excl_start;
        if (strategy == SearchNearest)
          strategy = SearchLeftmost;
        else if (strategy == SearchFarthest)
          strategy = SearchRightmost;
      }

      switch (strategy) {
      case SearchFarthest:

        maxdist = MAX(excl_start - lbound, rbound - excl_start);

        assert(maxdist >= 0);

        for (dist = maxdist; dist >= 0; dist--) {

          i = excl_start - dist;

          if (i >= lbound &&
              (inclusive || (i < excl_start)))
            if (eval_bool(constr, NULL, i)) {
              table[line] = i;
              break;
            }

          i = excl_start + dist;

          if (i <= rbound &&
              (inclusive || (i > excl_end)))
            if (eval_bool(constr, NULL, i)) {
              table[line] = i;
              break;
            }

          nr_evals++;
          if (nr_evals == 1000) {
            CheckForInterrupts();
            nr_evals = 0;
          }

        }
        break;

      case SearchNearest:

        maxdist = MAX(excl_start - lbound, rbound - excl_start);
        assert(maxdist >= 0);

        for (dist = 0; dist <= maxdist; dist++) {

          i = excl_start - dist;

          if (i >= lbound &&
              (inclusive || (i < excl_start)))
            if (eval_bool(constr, NULL, i)) {
              table[line] = i;
              break;
            }

          i = excl_start + dist;

          if (i <= rbound &&
              (inclusive || (i > excl_end)))
            if (eval_bool(constr, NULL, i)) {
              table[line] = i;
              break;
            }

          nr_evals++;
          if (nr_evals == 1000) {
            CheckForInterrupts();
            nr_evals = 0;
          }

        }
        break;

      case SearchLeftmost:
        for (i = lbound; i <= rbound; i++)
          if (inclusive || (i < excl_start) || (i > excl_end)) {
            if (eval_bool(constr, NULL, i)) {
              table[line] = i;
              break;
            }

            nr_evals++;
            if (nr_evals == 1000) {
              CheckForInterrupts();
              nr_evals = 0;
            }
          }
        break;

      case SearchRightmost:
        for (i = rbound; i >= lbound; i--)
          if (inclusive || (i < excl_start) || (i > excl_end)) {
            if (eval_bool(constr, NULL, i)) {
              table[line] = i;
              break;
            }

            nr_evals++;
            if (nr_evals == 1000) {
              CheckForInterrupts();
              nr_evals = 0;
            }
          }
        break;
      default:
        break;
      }
    }
  }

  if (progress_bar) 
    progress_bar_message(1, 1, "  cleaning up");

  switch (t_id) {
  case MatchField:
    for (i = 0; i < corp->size; i++) {
      if (table[i] >= 0) 
        corp->range[i].start = table[i];
      if (corp->range[i].start > corp->range[i].end)
        corp->range[i].start = corp->range[i].end;
    }
    cl_free(table);
    break;

  case MatchEndField:
    for (i = 0; i < corp->size; i++) {
      if (table[i] >= 0) 
        corp->range[i].end = table[i];
      if (corp->range[i].end < corp->range[i].start)
        corp->range[i].end = corp->range[i].start;
    }
    cl_free(table);
    break;

  case TargetField:
    cl_free(corp->targets);
    corp->targets = table;
    break;

  case KeywordField:
    cl_free(corp->keywords);
    corp->keywords = table;
    break;

  default:
    assert(0 && "Can't be");
    break;
  }

  if (progress_bar)
    progress_bar_clear_line();

  if ((t_id == MatchField) || (t_id == MatchEndField))
    RangeSort(corp, 0);                /* re-sort corpus if match regions were modified */

  touch_corpus(corp);  
  if (!EvaluationIsRunning) {
    cqpmessage(Warning, "Evaluation interruted: results may be incomplete.");
    if (which_app == cqp) install_signal_handler();
  }
  EvaluationIsRunning = 0;

  return 1;
}
Example #30
0
File: groups.c Project: cran/rcqp
Group *
ComputeGroupInternally(Group *group)
{
  ID_Count_Mapping node;
  ID_Count_Mapping *result;

  int i;
  size_t nr_nodes;
  int percentage, new_percentage; /* for ProgressBar */
  int size = group->my_corpus->size;

  /* ---------------------------------------------------------------------- */

  nr_nodes = 0;
  
  if (progress_bar)
    progress_bar_clear_line();
  percentage = -1;

  EvaluationIsRunning = 1;

  for (i = 0; i < size; i++) {
    if (! EvaluationIsRunning)
      break;                    /* user abort (Ctrl-C) */

    if (progress_bar) {
      new_percentage = floor(0.5 + (100.0 * i) / size);
      if (new_percentage > percentage) {
        percentage = new_percentage;
        progress_bar_percentage(1, 2, percentage);
      }
    }

    node.s = get_group_id(group, i, 0);       /* source ID */
    node.t = get_group_id(group, i, 1);       /* target ID */
    node.freq = 0;
  
    result = binsert_g(&node,
                       (void **) &(group->count_cells),
                       &nr_nodes,
                       sizeof(ID_Count_Mapping),
                       compare_st_cells);

    result->freq++;
  }

  if (EvaluationIsRunning) {
    group->nr_cells = sum_freqs(group->count_cells, nr_nodes, group->cutoff_frequency);
    
    if (progress_bar)
      progress_bar_clear_line();
    
    if (group->nr_cells < nr_nodes)
      group->count_cells = 
        cl_realloc(group->count_cells, (group->nr_cells * sizeof(ID_Count_Mapping)));
  }
  else {
    cqpmessage(Warning, "Group operation aborted by user.");
    if (which_app == cqp) install_signal_handler();
    free_group(&group);         /* sets return value to NULL to indicate failure */
  }
  EvaluationIsRunning = 0;
    
  return group;
}