Esempio n. 1
0
/* call_hist:
    Executes the nth history command
*/
void call_hist(int n)
{
    int i;
    char*tmpInput;
    HISTNODE *cur = history_tail;
    //Given int n, find history, then send that entire history string to parseinput
    for (i = 1; i < (n - 1); i++)
    {
        cur = cur->prev;
    }

    if((tmpInput = (char *) malloc(sizeof(cur->past_input))) == NULL)
    {
        // Memory allocation failed
        printf("error: %s", strerror(errno));
        return;
    }
    strcpy(tmpInput, cur->past_input);

    //Found the nth history node
    pop_hist_head(); //Pop the !n command that has already executed (must be before parseinput)

    parseinput(tmpInput);

    return;
}
Esempio n. 2
0
void Interpret(char expr[])
{
  SetIntSignal(True);
  if(commandline(expr))
    ;
  else if(seterror()==0)
  {
    initstack();
    restoretemplates();
    CloseAllIOFiles();
    interrupted = False;
    if(parseinput(expr))
      checkexpression(top(), True);
    else
    {
      checkexpression(top(), False);
      settop(modify_expression(top()));
      starttiming();
      toplevel();
      stoptiming();
    }
  }
  SetIntSignal(False);
  initstack();
  restoretemplates();
  CloseAllIOFiles();
  interrupted = False;
  Write("\n");
}
Esempio n. 3
0
int NDSSYSTEM::exec()
{
    while( parseinput() != -1 )
    {
        cpu->exec();
        vid->render2D();
        SDL_Flip(screen);

    }
    return 0;
}
Esempio n. 4
0
// main run of program
void main(){
  // initial variables for cipher
  FILE *inFile;
  FILE *outFile;
  inFile = fopen("caesarCipher.in", "r");
  outFile = fopen("caesarCipher.out", "w");
  int inSize = 256;
  char input[256] = "";
  int outSize = 310;
  char code[310] = "";
  char mode;
  int block = 5;
  int key;

  // set mode to cipher or decipher
  printf("Please type a 'D' to decrypt or leave blank for encrypt: ");
  scanf("%c", &mode);

  // get the key from user for creating cipher
  printf("Please enter the Caesar cipher key: ");
  scanf("%d", &key);
  if(mode == 'd' || mode == 'D')
    key = 26 - key;

  while(fgets(input, inSize, inFile) != NULL){
    // modify code: letters only & all caps
    parseinput(input, inSize, block, code);
    allcaps(code, inSize);

    // perform the Caesar cipher
    int i;
    for(i = 0; i < outSize; i++){
      if(code[i] >= 'A' && code[i] <= 'Z')
        code[i] = ((code[i] - 'A') + key) % 26 + 'A';
    }

    // write code to output
    fprintf(outFile, "%s\n", code);

    // reset strings for next iteration
    memset(&input[0], 0, inSize);
    memset(&code[0], 0, outSize);
  }

  // close files
  fclose(inFile);
  fclose(outFile);

  // print out success
  if(mode == 'd' || mode == 'D')
    printf("Your input is decoded in 'caesarCipher.out utilizing key %d.\n", 26-key);
  else
    printf("Your input is encoded in 'caesarCipher.out'utilizing key %d.\n", key);
}
Esempio n. 5
0
/*main:
    Main Shell, calls parseinput until notified to exit
*/
int main(int argc, char *argv[]) 
{
    char buf[BUF_SIZE];
    head = NULL;
    history_count = 0;
    history_head = NULL;
    history_tail = NULL;
    do {
        getinput(buf, sizeof(buf));
    } while (parseinput(buf) == 1);
    return 0;
}
Esempio n. 6
0
static int runfile () {
	if (!_program && !_system) {
		printf ("No program or system rule defined\n");
		return 1;
	}
	if (_stdin) {
		int f = open (_stdin, O_RDONLY);
		close (0);
		dup2 (f, 0);
	}
	if (_stdout) {
		int f = open (_stdout, O_WRONLY);
		close (1);
		dup2 (f, 1);
	}
	if (_stderr) {
		int f = open (_stderr, O_WRONLY);
		close (2);
		dup2 (f, 2);
	}

	if (_connect) {
		char *p = strchr (_connect, ':');
		if (p) {
			RSocket *fd = r_socket_new (0);
			*p=0;
			if (!r_socket_connect_tcp (fd, _connect, p+1, 30)) {
				eprintf ("Cannot connect\n");
				return 1;
			}
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (fd->fd, 0);
			dup2 (fd->fd, 1);
			dup2 (fd->fd, 2);
		} else {
			eprintf ("Invalid format for connect. missing ':'\n");
			return 1;
		}
	}
	if (_listen) {
		RSocket *child, *fd = r_socket_new (0);
		if (!r_socket_listen (fd, _listen, NULL)) {
			eprintf ("rarun2: cannot listen\n");
			return 1;
		}
		child = r_socket_accept (fd);
		if (child) {
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (child->fd, 0);
			dup2 (child->fd, 1);
			dup2 (child->fd, 2);
		}
	}
	if (_chgdir) chdir (_chgdir);
	if (_chroot) chdir (_chroot);
#if __UNIX__
	if (_chroot) {
		if (chroot (".")) {
			eprintf ("rarun2: cannot chroot\n");
			return 1;
		}
	}
	if (_setuid) setuid (atoi (_setuid));
	if (_seteuid) seteuid (atoi (_seteuid));
	if (_setgid) setgid (atoi (_setgid));
	if (_input) {
		int f2[2];
		pipe (f2);
		close (0);
		dup2 (f2[0], 0);
		parseinput (_input);
		write (f2[1], _input, strlen (_input));
	}
#endif
	if (_r2preload) {
		if (_preload) {
			eprintf ("WARNING: Only one library can be opened at a time\n");
		}
		_preload = R2_LIBDIR"/libr2."R_LIB_EXT;
	}
	if (_libpath) {
#if __WINDOWS__
		eprintf ("rarun2: libpath unsupported for this platform\n");
#elif __APPLE__
		r_sys_setenv ("DYLD_LIBRARY_PATH", _libpath);
#else
		r_sys_setenv ("LD_LIBRARY_PATH", _libpath);
#endif
	}
	if (_preload) {
#if __APPLE__
		// 10.6
		r_sys_setenv ("DYLD_PRELOAD", _preload);
		r_sys_setenv ("DYLD_INSERT_LIBRARIES", _preload);
		// 10.8
		r_sys_setenv ("DYLD_FORCE_FLAT_NAMESPACE", "1");
#else
		r_sys_setenv ("LD_PRELOAD", _preload);
#endif
	}
	if (_timeout) {
#if __UNIX__
		int mypid = getpid ();
		if (!fork ()) {
			sleep (_timeout);
			if (!kill (mypid, 0))
				eprintf ("\nrarun2: Interrupted by timeout\n");
			kill (mypid, SIGKILL);
			exit (0);
		}
#else
		eprintf ("timeout not supported for this platform\n");
#endif
	}
	if (_system) {
		exit (r_sys_cmd (_system));
	}
	if (!r_file_exists (_program)) {
		eprintf ("rarun2: %s: file not found\n", _program);
		return 1;
	}
	exit (execv (_program, _args));
}
Esempio n. 7
0
R_API int r_run_start(RRunProfile *p) {
#if __APPLE__
	posix_spawnattr_t attr = {0};
	pid_t pid = -1;
#endif
	int ret;
	if (!p->_program && !p->_system) {
		printf ("No program or system rule defined\n");
		return 1;
	}
	if (p->_stdin) {
		int f = open (p->_stdin, O_RDONLY);
		if (f < 0)
			return 1;
		close (0);
		dup2 (f, 0);
	}
	if (p->_stdout) {
		int f = open (p->_stdout, O_WRONLY);
		if (f < 0)
			return 1;
		close (1);
		dup2 (f, 1);
	}
	if (p->_stderr) {
		int f = open (p->_stderr, O_WRONLY);
		if (f < 0)
			return 1;
		close (2);
		dup2 (f, 2);
	}
	if (p->_aslr != -1)
		setASLR (p->_aslr);
#if __UNIX__
	set_limit (p->_docore, RLIMIT_CORE, RLIM_INFINITY);
	if (p->_maxfd)
		set_limit (p->_maxfd, RLIMIT_NOFILE, p->_maxfd);
#ifdef RLIMIT_NPROC
	if (p->_maxproc)
		set_limit (p->_maxproc, RLIMIT_NPROC, p->_maxproc);
#endif
	if (p->_maxstack)
		set_limit (p->_maxstack, RLIMIT_STACK, p->_maxstack);
#else
	if (p->_docore || p->_maxfd || p->_maxproc || p->_maxstack)
		eprintf ("Warning: setrlimits not supported for this platform\n");
#endif

	if (p->_connect) {
		char *q = strchr (p->_connect, ':');
		if (q) {
			RSocket *fd = r_socket_new (0);
			*q = 0;
			if (!r_socket_connect_tcp (fd, p->_connect, q+1, 30)) {
				eprintf ("Cannot connect\n");
				return 1;
			}
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (fd->fd, 0);
			dup2 (fd->fd, 1);
			dup2 (fd->fd, 2);
		} else {
			eprintf ("Invalid format for connect. missing ':'\n");
			return 1;
		}
	}
	if (p->_listen) {
		RSocket *child, *fd = r_socket_new (0);
		if (!r_socket_listen (fd, p->_listen, NULL)) {
			eprintf ("rarun2: cannot listen\n");
			r_socket_free (fd);
			return 1;
		}
		child = r_socket_accept (fd);
		if (child) {
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (child->fd, 0);
			dup2 (child->fd, 1);
			dup2 (child->fd, 2);
		}
	}
	if (p->_r2sleep != 0) {
		r_sys_sleep (p->_r2sleep);
	}
	if (p->_chgdir) {
		ret = chdir (p->_chgdir);
		if (ret < 0)
			return 1;
	}
	if (p->_chroot) {
		ret = chdir (p->_chroot);
		if (ret < 0)
			return 1;
	}
#if __UNIX__
	if (p->_chroot) {
		if (chroot (p->_chroot)) {
			eprintf ("rarun2: cannot chroot\n");
			return 1;
		}
		chdir("/");
	}
	if (p->_setuid) {
		ret = setgroups(0, NULL);
		if (ret < 0)
			return 1;
		ret = setuid (atoi (p->_setuid));
		if (ret < 0)
			return 1;
	}
	if (p->_seteuid) {
		ret = seteuid (atoi (p->_seteuid));
		if (ret < 0)
			return 1;
	}
	if (p->_setgid) {
		ret = setgid (atoi (p->_setgid));
		if (ret < 0)
			return 1;
	}
	if (p->_input) {
		int f2[2];
		pipe (f2);
		close (0);
		dup2 (f2[0], 0);
		parseinput (p->_input);
		write (f2[1], p->_input, strlen (p->_input));
	}
#endif
	if (p->_r2preload) {
		if (p->_preload) {
			eprintf ("WARNING: Only one library can be opened at a time\n");
		}
		p->_preload = R2_LIBDIR"/libr2."R_LIB_EXT;
	}
	if (p->_libpath) {
#if __WINDOWS__
		eprintf ("rarun2: libpath unsupported for this platform\n");
#elif __HAIKU__
		r_sys_setenv ("LIBRARY_PATH", p->_libpath);
#elif __APPLE__
		r_sys_setenv ("DYLD_LIBRARY_PATH", p->_libpath);
#else
		r_sys_setenv ("LD_LIBRARY_PATH", p->_libpath);
#endif
	}
	if (p->_preload) {
#if __APPLE__
		// 10.6
		r_sys_setenv ("DYLD_PRELOAD", p->_preload);
		r_sys_setenv ("DYLD_INSERT_LIBRARIES", p->_preload);
		// 10.8
		r_sys_setenv ("DYLD_FORCE_FLAT_NAMESPACE", "1");
#else
		r_sys_setenv ("LD_PRELOAD", p->_preload);
#endif
	}
	if (p->_timeout) {
#if __UNIX__
		int mypid = getpid ();
		if (!fork ()) {
			sleep (p->_timeout);
			if (!kill (mypid, 0))
				eprintf ("\nrarun2: Interrupted by timeout\n");
			kill (mypid, SIGKILL);
			exit (0);
		}
#else
		eprintf ("timeout not supported for this platform\n");
#endif
	}
#if __APPLE__
	posix_spawnattr_init (&attr);
	if (p->_args[0]) {
		char **envp = r_sys_get_environ();
		ut32 spflags = 0; //POSIX_SPAWN_START_SUSPENDED;
		spflags |= POSIX_SPAWN_SETEXEC;
		if (p->_aslr == 0) {
#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
			spflags |= _POSIX_SPAWN_DISABLE_ASLR;
		}
		(void)posix_spawnattr_setflags (&attr, spflags);
		if (p->_bits) {
			size_t copied = 1;
			cpu_type_t cpu;
#if __i386__ || __x86_64__
			cpu = CPU_TYPE_I386;
			if (p->_bits == 64)
				cpu |= CPU_ARCH_ABI64;
#else
			cpu = CPU_TYPE_ANY;
#endif
			posix_spawnattr_setbinpref_np (
					&attr, 1, &cpu, &copied);
		}
		ret = posix_spawnp (&pid, p->_args[0],
			NULL, &attr, p->_args, envp);
		switch (ret) {
		case 0:
			break;
		case 22:
			eprintf ("posix_spawnp: Invalid argument\n");
			break;
		case 86:
			eprintf ("posix_spawnp: Unsupported architecture\n");
			break;
		default:
			eprintf ("posix_spawnp: unknown error %d\n", ret);
			perror ("posix_spawnp");
			break;
		}
		exit (ret);
	}
#endif
	if (p->_system) {
		if (p->_pid) {
			eprintf ("PID: Cannot determine pid with 'system' directive. Use 'program'.\n");
		}
		exit (r_sys_cmd (p->_system));
	}
	if (p->_program) {
		if (!r_file_exists (p->_program)) {
			char *progpath = r_file_path (p->_program);
			if (progpath && *progpath) {
				free (p->_program);
				p->_program = progpath;
			} else {
				free (progpath);
				eprintf ("rarun2: %s: file not found\n", p->_program);
				return 1;
			}
		}
#if __UNIX__
		// XXX HACK close all non-tty fds
		{ int i; for (i=3; i<10; i++) close (i); }
		// TODO: use posix_spawn
		if (p->_setgid) {
			ret = setgid (atoi (p->_setgid));
			if (ret < 0)
				return 1;
		}
		if (p->_pid) {
			eprintf ("PID: %d\n", getpid ());
		}
		if (p->_pidfile) {
			char pidstr[32];
			snprintf (pidstr, sizeof (pidstr), "%d\n", getpid ());
			r_file_dump (p->_pidfile,
				(const ut8*)pidstr,
				strlen (pidstr), 0);
		}
#endif

	if (p->_nice) {
#if __UNIX__
        errno = 0;
        ret = nice(p->_nice);
        if (ret == -1) {
            if (errno != 0) {
                return 1;
            }
        }
#else
	eprintf ("nice not supported for this platform\n");
#endif
    }
		exit (execv (p->_program, (char* const*)p->_args));
	}
	return 0;
}
Esempio n. 8
0
int main(int argc, char *argv[]){
  int i,j;
#ifdef ONLINE
  char *cwd;
  int iarg, status;
  SIStream sis;
  char info[MAXLINE];
  memset(&sis, '\0', sizeof(SIStream));
#endif

  parseinput(argc, argv);

  syserror(0, "Starting up\n");

  /* install signal handler to catch SIGCHLD. Note that solaris uses
     SysV rather than BSD semantics and doesn't automaticall restart system
     calls like fread and fwrite.  So we use sigaction() rather than
     signal() so that we can set SA_RESTART. */
  {
    struct sigaction sig;
    memset(&sig, '\0', sizeof(sig));
    sig.sa_flags=SA_RESTART;
    sig.sa_handler=sighandler;
    if (sigaction(SIGCHLD, &sig, NULL)){
      syserror(1, "Unable to install signal handler for messages about troubled children\n");
    }
    if (sigaction(SIGTERM, &sig, NULL)){
      syserror(1, "Unable to install signal handler for logging output rate data and terminating\n");
    }
    if (sigaction(SIGUSR1, &sig, NULL)){
      syserror(1, "Unable to install signal handler for logging output rate data\n");
    }
  }

  for (i=0; i<npulsars; i++){
    char command[MAXLINE];
    char filename[MAXLINE];
    FILE *fpc=NULL;
    int length=0;
    char *newlineloc=NULL;

    /* construct file name */
    if (snprintf(filename, MAXLINE, "%s/in.%d", directory, i)>MAXLINE-1){
      syserror(0, "%s: file name %s/in.%d has more than MAXLINE=%d characters\n",
	      programname, directory, i, MAXLINE);
      exit(1);
    }

    /* open file */
    if (!(fpc=fopen(filename, "r"))) {
      syserror(1, "Can't open file %s for reading\n", filename);
      exit(1);
    }

    /* read command line from file */
    if (!(fgets(command, MAXLINE, fpc))){
      syserror(1, "Command line file %s was empty!\n", filename);
      exit(1);
    }
    fclose(fpc);

    /* check that contents are not too large */
    length=strlen(command);
    if (length>=MAXLINE-1) {
      syserror(0, "Command line file %s has line >= to MAXLINE=%d characters!\n",
	       filename, MAXLINE);
      exit(1);
    }

    /* replace first NEWLINE to null terminate string */
    if ((newlineloc=strchr(command, '\n')))
	*newlineloc='\0';

    /* append additional arguments to command line */
    /* GPS starttime */
    length=strlen(command);
    if (snprintf(command+length, MAXLINE-length, " -G %d", gpstime)>MAXLINE-length-1){
      command[length]='\0';
      syserror(0, "%s: command line has >= MAXLINE=%d characters\n", programname, MAXLINE);
      exit(1);
    }
    /* IFO */
    length=strlen(command);
    if ( snprintf(command+length, MAXLINE-length, " -I %s", ifo_name) > MAXLINE-length-1 ) {
      command[length]='\0';
      syserror(0, "%s: command line has >= MAXLINE=%d characters\n", programname, MAXLINE);
      exit(1);
    }
    /* Actuation-function if given */
    if (actuation)
      {
	length=strlen(command);
	if ( snprintf(command+length, MAXLINE-length, " --actuation=%s", actuation) > MAXLINE-length-1 ) {
	  command[length]='\0';
	  syserror(0, "%s: command line has >= MAXLINE=%d characters\n", programname, MAXLINE);
	  exit(1);
	}
      }

    /* now either show the command or execute it */
    if (show)
      printf("[%02d] %s\n", i, command);
    else {
      errno=0;
      if (!(fp[i]=popen(command, "r")) || errno){
	syserror(1, "Unable to popen(3) %s\n", command);
	exit(1);
      }
    }
  }

  /* a useful option for debugging -- show the output */
  if (show) {
    if (!npulsars)
      printf("%s: Warning: n=0 so an infinite-length zero strength signal will be made!\n", argv[0]);
    exit(0);
  }

#if 0
  {
    pid_t pid;
    int status;
    /* wait a couple of seconds, then check that all processes are running happily! */
    sleep(2);
    pid=waitpid(-1, &status, WNOHANG | WUNTRACED);
    if (pid) {
      syserror(0,"Subprocess with PID=%d is misbehaving.\n", (int)pid);
      if (WIFEXITED(status))
	syserror(0, "Subprocess or shell did exit(%d)\n", WEXITSTATUS(status));

      if (WIFSIGNALED(status))
	syserror(0, "Subprocess terminated because it caught signal %d [%s]\n",
		WTERMSIG(status), strsignal(WTERMSIG(status)));
      exit(1);
    }
  }
#endif

  /* processes opened, read data*/
  for (i=0; i<npulsars; i++){
    if (fread(&testval, sizeof(float), 1, fp[i]) != 1) {
      syserror(1, "Could not read first float 1234.5 from %d'th signal source\n", i);
      exit(1);
    } else if (testval != 1234.5) {
      syserror(0, "First value (%f) from %d'th signal source was not 1234.5\n", testval,  i);
      exit(1);
    } else if (fread(bufflen+i, sizeof(int), 1, fp[i]) != 1) {
      syserror(1, "Could not read buffer size from %d'th signal source\n", i);
      exit(1);
    } else if (bufflen[i]<sampling_rate || bufflen[i]>sampling_rate*60) {
      syserror(0, "Bad buffer size %d floats from %d'th signal source (expect %d <= size <= %d)\n", bufflen[i], i, sampling_rate, 60*sampling_rate);
      exit(1);
    } else if (bufflen[i]% BLOCKSIZE) {
      syserror(0, "Bad buffer size %d floats from %d'th signal source NOT a multiple of BLOCKSIZE=%d\n", bufflen[i], i, BLOCKSIZE);
      exit(1);
    } else if (!(buffs[i]=(float *)calloc(bufflen[i], sizeof(float)))) {
      syserror(1, "Can't allocate buffer of %d floats for %d'th signal source\n", bufflen[i], i);
      exit(1);
    }
    /* ensure that we read buffers on first pass */
    readfrombuff[i]=bufflen[i];
  }

  /* are we calling the excitation engine directly? */
  if (channel) {

#ifdef ONLINE
    /* Report some information about this injection client */
    cwd = getcwd( NULL, 256 );
    if ( cwd ) {
      sprintf( info, "%s %s", argv[0], cwd );
    } else {
      sprintf( info, "%s unknown_directory", argv[0] );
    }
    free( cwd );
    SIStrAppInfo( info );

    /* Open the Signal Injection Stream */
    status = SIStrOpen( &sis, channel, sampling_rate, (double) gpstime + starttime_offset_eff );
    if ( SIStr_debug ) {
      syserror(0, "SIStrOpen() returned %d\n", status );
    }
    if ( status != SIStr_OK ) {
      syserror(0, "SIStrOpen() error opening SIStream: %s\n", SIStrErrorMsg(status) );
      exit(2);
    }
#endif
  }
  else
    if (do_text)
    printf("1234.5\n");
  else {
    /* write out 1234.5 */
    if (1!=fwrite(&testval, sizeof(float), 1, stdout)){
      syserror(1, "Unable to output key value 1234.5\n");
      exit(1);
    }
  }

  /* now read data blocks unless a SIGTERM has set shutdown */
  while (!shutdown_pulsar_injection) {
    int num=0;
    int line;
    int tdelt=gpstime-tfiducial;

    /* clear block that will contain totals */
    for (j=0; j<BLOCKSIZE; j++)
      total[j]=0.0;

    /* if needed, insert calibration line(s) */
    for (line=0; line<3; line++){
      if (calamp[line] != 0.0) {
	/* normal int and double variables for integer/fractional
	   time.  In this and in the code that follows, _fra refers to
	   the fractional part [0,1) and _int refers to the integer
	   part. */

	double dt_fra;

	/*  Avoid long longs in inner loop as they are slow. */
	long long t_rem=blocks, t_int=BLOCKSIZE;

	/* line amplitude and frequency (integer + fractional parts) */
	double f_fra  = calfreq[line];
	int    f_int  = (int)f_fra;
	f_fra -= f_int;

	/* integer and fractional time offsets of first sample */
	t_rem   *= t_int;
	t_int    = t_rem;
	t_int   /= sampling_rate;
	t_rem   -= t_int*sampling_rate;
	t_int   += tdelt;

	// unused: int dt_int   = t_int;
	dt_fra   = t_rem;
	dt_fra  /= sampling_rate;

	for (j=0; j<BLOCKSIZE; j++) {
	  double cycles1, cycles2, cycles3;
	  double tlocal_fra  = dt_fra+(double)j/((double)sampling_rate);
	  int    tlocal_int  = (int)tlocal_fra;
	  tlocal_fra        -= tlocal_int;
	  tlocal_int        += t_int;
	  cycles1            = f_fra*tlocal_int;
	  cycles1           -= (int)cycles1;
	  cycles2            = tlocal_fra*f_int;
	  cycles2           -= (int)cycles2;
	  cycles3            = tlocal_fra*f_fra;
	  cycles3           -= (int)cycles3;

	  total[j]=calamp[line]*sin(2*LAL_PI*(cycles1+cycles2+cycles3));
	}
      }
    }

    /* loop over the different pulsars */
    for (i=0; i<npulsars; i++) {
      float *where;

      if (readfrombuff[i]==bufflen[i]){
	/* read data from the i'th signal */
	if (bufflen[i]!=(num=fread(buffs[i], sizeof(float), bufflen[i], fp[i]))){
	  syserror(1, "Only read %d floats (not %d) from %d'th signal source\n", num, bufflen[i], i);
	  exit(1);
	}
#ifdef DEBUGTIMING
	syserror(0, "just read %d seconds of data from %d'th signal\n", num/sampling_rate, i);
#endif
	readfrombuff[i]=0;
      }

      /* location of signal in buffer */
      where=buffs[i]+readfrombuff[i];

      /* add i'th pulsar to the total signal */
      for (j=0; j<BLOCKSIZE; j++)
	total[j]+=where[j];

      readfrombuff[i]+=BLOCKSIZE;
    }

    /* now output the total signal to frames */

    if (write_frames) {
#ifdef HAVE_LIBLALFRAME
	static int counter = 0;
	static FrFile *oFile;

	FrameH *frame;
	FrSimData *sim;

	int m, level = 0;
	long ndata = BLOCKSIZE;
	char framename[256];
	struct stat statbuf;

	/* This leads to a names like: CW_Injection-921517800-60.gwf */
	sprintf(framename, "CW_Injection");
	frame = FrameHNew(framename);
	if (!frame) {
	    syserror(1, "FrameNew failed (%s)", FrErrorGetHistory());
	    exit(1);
	}

	/* set up GPS time, sample interval, copy data */
	frame->GTimeS = gpstime + counter;
	frame->GTimeN = 0;
	frame->dt = ndata/sampling_rate;
        char frName[] = "CW_simulated";
	sim = FrSimDataNew(frame, frName, sampling_rate, ndata, -32);
	for (m=0; m < ndata; m++) {
	    sim->data->dataF[m] = total[m];
	}

	/* open framefile, to contain secs_per_framefile of data */
	if (!counter) {
	    oFile = FrFileONewM(framename, level, argv[0], secs_per_framefile);
	    if (!oFile) {
		syserror(1, "Cannot open output file %s\n", framename);
		exit(1);
	    }
	    /* Turn off the 'framefile boundary alignment'.  Without this one gets:
	       CW_Injection-921517807-3.gwf
	       CW_Injection-921517810-10.gwf
	       CW_Injection-921517820-10.gwf
	       ...
	       With this one gets
	       CW_Injection-921517807-10.gwf
	       CW_Injection-921517817-10.gwf
	       ...
	    */
	    oFile->aligned  = FR_NO;
	}

	/* write data to framefile */
	if (FR_OK != FrameWrite(frame, oFile)) {
	    syserror(1, "Error during frame write\n"
		     "  Last errors are:\n%s", FrErrorGetHistory());
	    exit(1);
	}

	/* free memory for frames and for simdata structures */
	FrameFree(frame);

	/* Do we keep a limited set of frames on disk? */
	if (write_frames>1) {
	    char listname[256];
	    int watchtime = gpstime + secs_per_framefile*(counter/secs_per_framefile - write_frames + 1);
	    sprintf(listname, "CW_Injection-%d-%d.gwf",  watchtime, secs_per_framefile);
	    /* syserror(0, "Watching for file %s to disappear....\n", listname); */
	    while (!stat(listname, &statbuf)) {
		/* if enough files already in place, then sleep 0.1 seconds */
		struct timespec rqtp;
		rqtp.tv_sec = 0;
		rqtp.tv_nsec = 100000000;
		nanosleep(&rqtp, NULL);
	    }
	}

	/* increment counter for the next second */
	counter++;
#else
	syserror(0, "ERROR: write_frames!=0, but binary was built without Frame support\n" );
        exit(1);
#endif
    } /* if (write_frames) */

    /* now output the total signal... */
    else if (channel){
#ifdef ONLINE
      /* ... to the excitation engine ... */
      status = SIStrAppend( &sis, total, BLOCKSIZE, 1.0 );
      if ( SIStr_debug >= 2 )
	syserror(0, "SIStrAppend() returned %d\n", status );
      if ( status != SIStr_OK ) {
	syserror(0, "SIStrAppend() error adding data to stream: %s\n",
		  SIStrErrorMsg(status) );
	break;
      }
#endif
    }
    /* ... or as text ... */
    else if (do_text){
      if (do_axis){
	/* ... either as text with both x and y axes ... */
	long long x1=gpstime;
	long long E9=1000000000;
	x1*=E9;
        x1 += (long long)(starttime_offset_eff * E9 );	/* account for startime-shift, consistent with CHANNEL injection */

	for (j=0; j<BLOCKSIZE; j++){
	  long long x2=count, x3;
	  x2 *= E9;
	  x2  /= (sampling_rate);
	  x2 += x1;
	  x3 =  x2;
	  x3 /= E9;
	  x2 -= x3*E9;
	  printf("%lld.%09lld %g\n", x3, x2, total[j]);
	  count++;
	}
      }
      else {
	/* ... or as y-axis text only ... */
	for (j=0; j<BLOCKSIZE; j++)
	  printf("%g\n", total[j]);
      }
    }
    else {
      /* ... or in raw binary form. */
      if (BLOCKSIZE!=(num=fwrite(total, sizeof(float), BLOCKSIZE, stdout))){
	syserror(1, "Only wrote %d values (not %d)\n", num, BLOCKSIZE);
	exit(1);
      }
#ifdef DEBUGTIMING
      syserror(0, "Just sent %d seconds of data to system\n", BLOCKSIZE/sampling_rate);
      sleep(BLOCKSIZE/sampling_rate);
#endif
    }

    /* increment counter of blocks sent out */
    blocks++;
  }

  /* We'll be exiting, so clean up */
  if (channel) {
#ifdef ONLINE
    /* Close the signal injection stream */
    status = SIStrClose( &sis );
    if ( SIStr_debug )
      syserror(0, "SIStrClose returned %d\n", status );
    if ( status != SIStr_OK ) {
      syserror(0, "Error while closing SIStream: %s\n", SIStrErrorMsg(status) );
      exit(2);
    }
#endif
  }

#ifdef _LINUX
  /* shut down signal handler for SIGCHLD */
  {
    struct sigaction sig;
    memset(&sig, '\0', sizeof(sig));
    sig.sa_flags=SA_RESTART | SA_NOCLDSTOP;
    sig.sa_handler=SIG_IGN;
    if (sigaction(SIGCHLD, &sig, NULL)){
      syserror(1, "Unable to install signal handler for exiting\n");
    }
    if (sigaction(SIGPIPE, &sig, NULL)){
      syserror(1, "Unable to install signal handler for exiting\n");
    }
  }

  for (i=0; i<npulsars; i++) {
    int status;

    __fpurge(fp[i]);
    status=pclose(fp[i]);
    if (status!=-1)
      syserror(0, "The %d'th signal generator did exit(%d)\n", i, (int)WEXITSTATUS(status));
    else {
      syserror(1, "Trouble shutting down the %d'th signal generator\n", i);
      exit(1);
    }
  }
#endif

  /* and exit cleanly */
  exit(0);
}
Esempio n. 9
0
/*
 * Main entry point
 */
int main(int argc, char *argv[]) {
    p = parseopts(argc, argv);

    if (p == INVALID_PARAMETER) {
        usage(EXIT_FAILURE);
    }

    int num_params = parseinput(argc, argv);

    if (num_params == 0) {
        usage(EXIT_FAILURE);
    }

    // Everything should be okay from here on

    double sigma = MODEL_PARAMS[s].sigma;
    double epsilon = MODEL_PARAMS[s].epsilon;
    double m = MODEL_PARAMS[s].m;
    double r = MODEL_PARAMS[s].r_nn;

    if (p == OMEGA || p == GAMMA) {
        vec3 dq = { 0, 0, 0 };

        if (num_params == 2) {
            dq[X] = (q2[X] - q1[X])/(npoints - 1);
            dq[Y] = (q2[Y] - q1[Y])/(npoints - 1);
            dq[Z] = (q2[Z] - q1[Z])/(npoints - 1);
        }

        if (p == OMEGA) {
            vec3 omega;
            double a = A(epsilon, sigma, r);
            double b = B(epsilon, sigma, r);

            if (num_params == 1) {
                frequencies(a, b, m, q1, omega, NULL);
                print_result(q1, omega);
            }

            else if (num_params == 2) {
                for (int i = 0; i < npoints; i++) {
                    frequencies(a, b, m, q1, omega, NULL);
                    print_result(q1, omega);
                    q1[X] += dq[X];
                    q1[Y] += dq[Y];
                    q1[Z] += dq[Z];
                }
            }

        }

        else { // Gamma
            vec3 gamma;
            double delta = 1e-20;

            if (num_params == 1) {
                calc_gamma(gamma, q1, delta, r, sigma, epsilon, m);
                print_result(q1, gamma);
            }

            else if (num_params == 2) {
                for (int i = 0; i < npoints; i++) {
                    calc_gamma(gamma, q1, delta, r, sigma, epsilon, m);
                    print_result(q1, gamma);
                    q1[X] += dq[X];
                    q1[Y] += dq[Y];
                    q1[Z] += dq[Z];
                }
            }
        }
    }

    else { // Cv
        double cv;

        if (num_params == 1) {
            cv = calc_cv(t1, r, sigma, epsilon, m);
            printf("%g %g\n", t1, cv);
        }

        else if (num_params == 2) {
            double dt = (t2 - t1)/(npoints - 1);

            for (int i = 0; i < npoints; i++) {
                cv = calc_cv(t1, r, sigma, epsilon, m);
                printf("%g %g\n", t1, cv);
                t1 += dt;
            }
        }
    }

    return 0;
}
Esempio n. 10
0
static int runfile () {
	if (!_program) {
		printf ("No program rule defined\n");
		return 1;
	}
	if (_stdin) {
		int f = open (_stdin, O_RDONLY);
		close (0);
		dup2 (f, 0);
	}
	if (_stdout) {
		int f = open (_stdout, O_RDONLY);
		close (1);
		dup2 (f, 1);
	}
	if (_stderr) {
		int f = open (_stderr, O_RDONLY);
		close (2);
		dup2 (f, 2);
	}

	if (_connect) {
		char *p = strchr (_connect, ':');
		if (p) {
			RSocket *fd = r_socket_new (0);
			*p=0;
			if (!r_socket_connect_tcp (fd, _connect, p+1, 30)) {
				eprintf ("Cannot connect\n");
				return 1;
			}
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (fd->fd, 0);
			dup2 (fd->fd, 1);
			dup2 (fd->fd, 2);
		} else {
			eprintf ("Invalid format for connect. missing ':'\n");
			return 1;
		}
	}
	if (_listen) {
		RSocket *child, *fd = r_socket_new (0);
		if (!r_socket_listen (fd, _listen, NULL)) {
			eprintf ("rarun2: cannot listen\n");
			return 1;
		}
		child = r_socket_accept (fd);
		if (child) {
			eprintf ("connected\n");
			close (0);
			close (1);
			close (2);
			dup2 (child->fd, 0);
			dup2 (child->fd, 1);
			dup2 (child->fd, 2);
		}
	}
	if (_chgdir) chdir (_chgdir);
	if (_chroot) chdir (_chroot);
#if __UNIX__
	if (_chroot) {
		if (chroot (".")) {
			eprintf ("rarun2: cannot chroot\n");
			return 1;
		}
	}
	if (_setuid) setuid (atoi (_setuid));
	if (_seteuid) seteuid (atoi (_seteuid));
	if (_setgid) setgid (atoi (_setgid));
	if (_input) {
		int f2[2];
		pipe (f2);
		close (0);
		dup2 (f2[0], 0);
		parseinput (_input);
		write (f2[1], _input, strlen (_input));
	}
#endif
	if (_preload) {
#if __APPLE__
		r_sys_setenv ("DYLD_PRELOAD", _preload);
#else
		r_sys_setenv ("LD_PRELOAD", _preload);
#endif
	}
	if (_timeout) {
#if __UNIX__
		int mypid = getpid ();
		if (!fork ()) {
			sleep (_timeout);
			if (!kill (mypid, 0))
				fprintf (stderr, "\nrarun2: Interrupted by timeout\n");
			kill (mypid, SIGKILL);
			exit (0);
		}
#else
		eprintf ("timeout not supported for this platform\n");
#endif
	}
	if (!r_file_exists (_program)) {
		eprintf ("rarun2: %s: file not found\n", _program);
		return 1;
	}
	exit (execv (_program, _args));
}