Exemplo n.º 1
0
        int vod_main(int argc, char * argv[])
        {
            util::daemon::Daemon my_daemon("peer_worker.conf");
            char const * default_argv[] = {
                "++framework::logger::Stream.0.file=$LOG/peer_worker.log", 
                "++framework::logger::Stream.0.append=true", 
                "++framework::logger::Stream.0.roll=true", 
                "++framework::logger::Stream.0.level=5", 
                "++framework::logger::Stream.0.size=102400", 
            };
            my_daemon.parse_cmdline(sizeof(default_argv) / sizeof(default_argv[0]), default_argv);
            my_daemon.parse_cmdline(argc, (char const **)argv);

            framework::process::SignalHandler sig_handler(
                framework::process::Signal::sig_int, 
                boost::bind(&util::daemon::Daemon::post_stop, &my_daemon), true);

            framework::logger::load_config(my_daemon.config());

            ppbox::common::log_versions();

            ppbox::common::CommonModule & common = 
                util::daemon::use_module<ppbox::common::CommonModule>(my_daemon, "VodWorker");
            common.set_version(ppbox::peer_worker::version());

            //util::daemon::use_module<ppbox::common::ConfigMgr>(my_daemon);
            util::daemon::use_module<ppbox::common::Debuger>(my_daemon);
            util::daemon::use_module<ppbox::common::PortManager>(my_daemon);
            util::daemon::use_module<ppbox::peer_worker::WorkerModule>(my_daemon);
            util::daemon::use_module<ppbox::peer_worker::StatusProxy>(my_daemon);

            my_daemon.start(framework::process::notify_wait);

            return 0;
        }
Exemplo n.º 2
0
int main()
{
    pthread_spinlock_t spinlock;
    struct sigaction act;

    /* Set up child thread to handle SIGALRM */
    act.sa_flags = 0;
    act.sa_handler = sig_handler;
    sigfillset(&act.sa_mask);
    sigaction(SIGALRM, &act, 0);

    printf("main: attemp to lock an un-initialized spin lock\n");

    printf("main: Send SIGALRM to me after 5 secs\n");
    alarm(5);

    /* Attempt to lock an uninitialized spinlock */
    rc = pthread_spin_lock(&spinlock);

    /* If we get here, call sig_handler() to check the return code of
     * pthread_spin_lock() */
    sig_handler();

    /* Unlock spinlock */
    pthread_spin_unlock(&spinlock);

    /* Destroy spinlock */
    pthread_spin_destroy(&spinlock);

    return PTS_PASS;
}
Exemplo n.º 3
0
int main(int argc, char * argv[])
{
    util::daemon::Daemon my_daemon("ppbox_transfer.conf");
    char const * default_argv[] = {
        "++Logger.stream_count=1", 
        "++Logger.ResolverService=1", 
        "++LogStream0.file=$LOG/ppbox_transfer.log", 
        "++LogStream0.append=true", 
        "++LogStream0.level=5", 
    };
    my_daemon.parse_cmdline(sizeof(default_argv) / sizeof(default_argv[0]), default_argv);
    my_daemon.parse_cmdline(argc, (char const **)argv);

    framework::process::SignalHandler sig_handler(
        framework::process::Signal::sig_int, 
        boost::bind(&util::daemon::Daemon::post_stop, &my_daemon), true);

    framework::logger::global_logger().load_config(my_daemon.config());

    util::daemon::use_module<ppbox::demux::DemuxerModule>(my_daemon);
    util::daemon::use_module<ppbox::mux::MuxerModule>(my_daemon);

    tools::transfer::TransferModule & module = 
        util::daemon::use_module<tools::transfer::TransferModule>(my_daemon);
    
    my_daemon.start(framework::this_process::notify_wait);

    return module.error().value();
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
    if(argc==1) {
        fprintf(stderr,"%s",usage);
        return 0;
    }
    if(argc>=2 && !strcmp(argv[1],"-9") ) {
        force=SIGKILL;
    }
    pgrp = setpgrp(); //it returns 0...
    pgrp = getpgrp();

    childpid = fork();
    if(!childpid) if(execvp(argv[1+!!force],argv+1+!!force)) {
            fprintf(stderr, MYNAME ": can't start subprocess, error in execvp().\n");
            return -1;
        }
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = sig_handler;
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGKILL, &sa, NULL);
    sigaction(SIGQUIT, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);

    prctl(PR_SET_PDEATHSIG, SIGTERM); //we ask the kernel to send a SIGTERM to pgroup, when its parent is terminated

    int wait_stat;
    wait(&wait_stat); //we wait until any of the subprocesses exit
    sig_handler(SIGTERM);
}
Exemplo n.º 5
0
int			main(int argc, char **argv)
{
    if (main_init(argc, argv) == -1)
        sig_handler(-1);
    while (42)
    {
        play_turn();
    }
    exit_shmem();
    return (EXIT_SUCCESS);
}
Exemplo n.º 6
0
int readresponse(int serverfd, messagedef_t *responsedef) {
    /* N.B. this could happen at a later time */
    /* 2. Read the response */
    /* 2.1 Read response message */
    int n=0;
    char*         responsebuf = NULL;
    if ((n = bufread(serverfd, responsedef, sizeof(messagedef_t))) != sizeof(messagedef_t)) {
        fprintf(stderr, "packet size = %d, should be %d\n", n, sizeof(messagedef_t));
        sig_handler(-1);
    }
    /* 2.2 Read response data if needed */
    if (responsedef->bufsize>0) {
        responsebuf = malloc(responsedef->bufsize);
        if ((n = bufread(serverfd, responsebuf, responsedef->bufsize)) != responsedef->bufsize) {
            fprintf(stderr, "read size = %d, should be %d\n", n, responsedef->bufsize);
            sig_handler(-1);
        }
        /* ignore the response and free the memory */
        free(responsebuf);
    }
    return 0;
}
Exemplo n.º 7
0
int main(int argc, char **argv)
{
  double command_tv = 0.0, command_rv = 0.0;
  char c;
  int quit = 0;
  double f_timestamp;

  carmen_ipc_initialize(argc, argv);
  carmen_param_check_version(argv[0]);

  // Initialize keybord, joystick and IPC
  carmen_initialize_keyboard();
  if (carmen_initialize_joystick(&joystick) >= 0) 
    no_joystick = 0;

  read_parameters(argc, argv);

  signal(SIGINT, sig_handler);
  
  f_timestamp = carmen_get_time();
  while(quit>=0) {
    carmen_ipc_sleep(0.05);
    if(!no_joystick && carmen_get_joystick_state(&joystick) >= 0) {
      carmen_joystick_control(&joystick, max_tv, max_rv,
			      &command_tv, &command_rv);
      carmen_robot_velocity_command(command_tv, command_rv);
      f_timestamp = carmen_get_time();
    }
    else if(carmen_read_char(&c)) {
      quit = carmen_keyboard_control(c, max_tv, max_rv,
				     &command_tv, &command_rv);
      carmen_robot_velocity_command(command_tv, command_rv);
      f_timestamp = carmen_get_time();
    }
    else if(carmen_get_time() - f_timestamp > 0.5) {
      carmen_robot_velocity_command(command_tv, command_rv);
      f_timestamp = carmen_get_time();
    }
  }
  sig_handler(SIGINT);
  return 0;
}
Exemplo n.º 8
0
void* sigmgr_thread()
{
	sigset_t   waitset, oset;
	siginfo_t  info;
	int        rc;
	pthread_t  ppid = pthread_self();

	pthread_detach(ppid);

	sigemptyset(&waitset);
	sigaddset(&waitset, SIGRTMIN);
	sigaddset(&waitset, SIGUSR1);

	while (1)  {
		rc = sigwaitinfo(&waitset, &info);
		if (rc != -1) {
			printf("sigwaitinfo() fetch the signal - %d\n", rc);
			sig_handler(info.si_signo);
		} else {
			printf("sigwaitinfo() returned err: %d; %s\n", errno, strerror(errno));
		}
	}
}
Exemplo n.º 9
0
int main(int argc, char *argv[])
{
    struct donut_ring *shared_ring;
    int i,j,k;
    int donuts[NUMFLAVORS][12];
    int counter[NUMFLAVORS];
    
    
    //Signal catching 
    sigset_t mask_sigs;
    int nsigs;
    struct sigaction new_action;
    int sigs[] = {SIGHUP,SIGINT,SIGQUIT,SIGBUS,SIGTERM,SIGSEGV,SIGFPE};
    nsigs = sizeof(sigs)/sizeof(int);
    sigemptyset(&mask_sigs);
    for (i = 0; i< nsigs ; i++)
    {
        sigaddset(&mask_sigs,sigs[i]);
    }
    for (i = 0; i < nsigs; i++)
    {
        new_action.sa_handler = sig_handler;
        new_action.sa_mask = mask_sigs;
        new_action.sa_flags = 0;
        
        if (sigaction (sigs[i],&new_action,NULL) == -1)
        {
            perror("can't set signals: ");
            exit(1);
        }
    }
    //shared memory
    if ((shmid = shmget(MEMKEY, sizeof (struct donut_ring), 0)) == -1)
    {
        perror("shared get failed: ");
        exit(1);
    }
    if ((shared_ring = shmat(shmid,NULL,0)) == (void *) -1)
    {
        perror("shared attach failed: ");
    }
    //shemaphores
    for (i = 0; i<NUMSEMIDS; i++)
    {
        if ((semid[i] = semget(SEMKEY+i, NUMFLAVORS, 0)) == -1)
        {
            perror("semaphore allocation failed: ");
        }
    }
    
    for (i = 0;i < 10; i++)
    {
        for (k = 0;k<NUMFLAVORS;k++)
        {
            counter[k] = 0;
        }
        for (k = 0;k<12;k++)
        {
            j = get_random_number();
            int donut_outptr;
            //take ticket
            if (p(semid[CONSUMER],j) == -1)
            {
                sig_handler(-1);
            }
            //lock the outptr
            if (p(semid[OUTPTR],j) == -1)
            {
                sig_handler(-1);
            }
            donuts[j][counter[j]] = shared_ring->flavor[j][shared_ring->outptr[j]];
            shared_ring->outptr[j]=(shared_ring->outptr[j] + 1) % NUMSLOTS;
            //unlock the outptr
            if (v(semid[OUTPTR],j) == -1)
            {
                sig_handler(-1);
            }
            //allow producer to make another donut in that slot
            if (v(semid[PROD],j) == -1)
            {
                sig_handler(-1);
            }
            printf("Donut: %d\tSerial Number: %d\n",j,donuts[j][counter[j]]);
            counter[j]++;
        }
        
        //print out of donut information
        struct timeval tv; 
        struct tm* ptm; 
        char time_string[40]; 
        long useconds; 
        gettimeofday (&tv, NULL); 
        ptm = localtime (&tv.tv_sec); 
        strftime (time_string, sizeof (time_string), "%H:%M:%S", ptm); 
        useconds = tv.tv_usec; 
        printf("------------------------------------------------------------------------\n");
        printf("consumer process PID: %d\ttime: %s.%06ld\t dozen #: %d\n",getpid(),time_string, useconds,i);
        printf("\n");
        printf("plain\tjelly\tcoconut\thoney-dip\n");
        for (k = 0;k<12;k++)
        {
            int rowtest = 0;
            for (j = 0; j< NUMFLAVORS; j++)
            {
                if (counter[j] > k)
                {
                    printf("%d\t",donuts[j][k]);
                    rowtest++;
                }
                else
                {
                    printf("\t");
                }
            }
            if (rowtest > 0)
            {
                printf("\n");
            }
        }
        printf("\r");
        printf("------------------------------------------------------------------------\n");
        printf("\n");
        
        //microsleep to give up CPU
        usleep(100);
    }
    return 0;
}
Exemplo n.º 10
0
int
main(int argc, char **argv)
{
    int max_tries = 5;
    int try;

    char username[32];
    int optidx = 0;

    int ask = 1;
    struct sigaction sa;

    setprogname(argv[0]);

#ifdef KRB5
    {
	krb5_error_code ret;

	ret = krb5_init_context(&context);
	if (ret)
	    errx (1, "krb5_init_context failed: %d", ret);
    }
#endif

    openlog("login", LOG_ODELAY | LOG_PID, LOG_AUTH);

    if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
		&optidx))
	usage (1);
    argc -= optidx;
    argv += optidx;

    if(help_flag)
	usage(0);
    if (version_flag) {
	print_version (NULL);
	return 0;
    }
	
    if (geteuid() != 0)
	errx(1, "only root may use login, use su");

    /* Default tty settings. */
    stty_default();

    if(p_flag)
	copy_env();
    else {
	/* this set of variables is always preserved by BSD login */
	if(getenv("TERM"))
	    add_env("TERM", getenv("TERM"));
	if(getenv("TZ"))
	    add_env("TZ", getenv("TZ"));
    }

    if(*argv){
	if(strchr(*argv, '=') == NULL && strcmp(*argv, "-") != 0){
	    strlcpy (username, *argv, sizeof(username));
	    ask = 0;
	}
    }

#if defined(DCE) && defined(AIX)
    esetenv("AUTHSTATE", "DCE", 1);
#endif

    /* XXX should we care about environment on the command line? */

    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = sig_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGALRM, &sa, NULL);
    alarm(login_timeout);

    for(try = 0; try < max_tries; try++){
	struct passwd *pwd;
	char password[128];
	int ret;
	char ttname[32];
	char *tty, *ttyn;
        char prompt[128];
#ifdef OTP
        char otp_str[256];
#endif

	if(ask){
	    f_flag = 0;
#if 0
	    r_flag = 0;
#endif
	    ret = read_string("login: "******"");
        }
        else
#endif

        {
#ifdef OTP
           if(auth_level && strcmp(auth_level, "otp") == 0 &&
                 otp_challenge(&otp_ctx, username,
                            otp_str, sizeof(otp_str)) == 0)
                 snprintf (prompt, sizeof(prompt), "%s's %s Password: "******"Password: "******"Login incorrect.\n");
	    ask = 1;
	    continue;
	}

	if(f_flag == 0 && check_password(pwd, password)){
	    fprintf(stderr, "Login incorrect.\n");
            ask = 1;
	    continue;
	}
	ttyn = ttyname(STDIN_FILENO);
	if(ttyn == NULL){
	    snprintf(ttname, sizeof(ttname), "%s??", _PATH_TTY);
	    ttyn = ttname;
	}
	if (strncmp (ttyn, _PATH_DEV, strlen(_PATH_DEV)) == 0)
	    tty = ttyn + strlen(_PATH_DEV);
	else
	    tty = ttyn;

	if (login_access (pwd, remote_host ? remote_host : tty) == 0) {
	    fprintf(stderr, "Permission denied\n");
	    if (remote_host)
		syslog(LOG_NOTICE, "%s LOGIN REFUSED FROM %s",
		       pwd->pw_name, remote_host);
	    else
		syslog(LOG_NOTICE, "%s LOGIN REFUSED ON %s",
		       pwd->pw_name, tty);
	    exit (1);
	} else {
	    if (remote_host)
		syslog(LOG_NOTICE, "%s LOGIN ACCEPTED FROM %s ppid=%d",
		       pwd->pw_name, remote_host, (int) getppid());
	    else
		syslog(LOG_NOTICE, "%s LOGIN ACCEPTED ON %s ppid=%d",
		       pwd->pw_name, tty, (int) getppid());
	}
        alarm(0);
	do_login(pwd, tty, ttyn);
    }
    exit(1);
}
Exemplo n.º 11
0
Arquivo: main.c Projeto: Elekhyr/ran
void process(void (*function)(int*, const int), int *t, int n, struct to_print* toPrint, FILE *fd){

    char buf[128];
    int pipefd[2];
    int f, i;
    clock_t start, end;
    double temp;

    temp = 0.0;
    success = 1;
    if(pipe(pipefd) < 0){
        perror("pipe");
        exit(1);
    }
    f = fork();
    if (f < 0){
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if (f == 0) {
        for(i = 0; i < 20; i++) {
            generate_array(t, n);
            sig_handler(SIGALRM, sigalarm_func, NULL);
            close(pipefd[0]);

            alarm(max_time);
            start = clock();
            (*function)(t, n);
            end = clock();
            alarm(0);

            for (i = 0; i < n-1; i++) {
                if (t[i] > t[i + 1]) {
                    kill(getppid(), SIGUSR1);
                    close(pipefd[1]);
                    exit(1);
                }

            }
            sprintf(buf, "%lf \n", ((double) end - start) / CLOCKS_PER_SEC);

            write(pipefd[1], buf, 5);

            close(pipefd[1]);
        }
        exit(EXIT_SUCCESS);
    }
    else{
        close(pipefd[1]);
        sig_handler(SIGUSR1, sigusr_func, NULL);
        int nb;
        while((nb = read(pipefd[0], buf, 5)) > 0){
            temp += atof(buf);
        }
        close(pipefd[0]);
        wait(NULL);
        toPrint->is_success = success;
        toPrint->computing_time = temp;
        if(toPrint->is_success){
            nb = sprintf(buf, "%s : [SUCCESS] in %lf \n", toPrint->name,atof(buf));
            write(1, buf, (size_t) nb);
        }
        else{
            nb = sprintf(buf, "%s : [FAIL] %s \n", toPrint->name, nb > 0 ? "Not sorted" : "Timeout" );
            write(2, buf, (size_t) nb);
        }
        print_results(*toPrint, fd);
        fflush(fd);
    }


}
Exemplo n.º 12
0
int main(int argc, char *argv[]) {
    struct emokit_device* d;
    struct emokit_frame c;

    int32_t i, j, k, nsamp = 0, nblk=0, si=0, status = 0, verbose = 1;
    int32_t putdatrequestsize=0;
    long int elapsedusec=0, printtime=0;
    struct timeval starttime, curtime;
    host_t buffhost;

    /* these represent the acquisition system properties */
    int nchans         = NCHANS;
    int fsample        = FSAMPLE;
    int blocksize      = roundf(fsample/((float)BUFFRATE));
    int channamesize   = 0;
    char *labelsbuf    = NULL;

    /* these are used in the communication and represent statefull information */
    int serverfd             = -1;
    message_t     request;
    char          *requestbuf = NULL;
    data_t        data;
    emokit_samp_t *samples=NULL;
    message_t     *response = NULL;
    messagedef_t  responsedef;
    header_t      header;
    ft_chunkdef_t chunkdef; // for holding the channel names

    if ( argc==1 ) usage();
    if ( argc>1 && (strcmp(argv[1],"-help")==0 || strcmp(argv[1],"-h")==0) ) {
        usage();
        sig_handler(0);
    }

    if (argc>1) {
        char *fname=argv[1];
        int ci=0;
        /* find the which splits the host and port info */
        for (ci=0; fname[ci]!=0; ci++) {
            if ( fname[ci]==':' ) { /* parse the port info */
                buffhost.port=atoi(&(fname[ci+1]));
                break;
            }
        }
        memcpy(buffhost.name,fname,ci);
        buffhost.name[ci]=0; /* copy hostname out and null-terminate */
    }
    else {
        sprintf(buffhost.name, "%s", DEFAULT_HOSTNAME);
        buffhost.port = DEFAULT_PORT;
    }

    if (verbose>0) fprintf(stderr, "emokit2ft: buffer = %s:%d\n", buffhost.name,buffhost.port);

    if ( argc>2 ) {
        BUFFRATE = atoi(argv[2]);
        blocksize = (int)(roundf(fsample/((float)BUFFRATE)));
    }
    if (verbose>0) fprintf(stderr, "emokit2ft: BUFFRATE = %d\n", BUFFRATE);
    if (verbose>0) fprintf(stderr, "emokit2ft: blocksize = %d\n", blocksize);

    //-------------------------------------------------------------------------------
    // open the emotive device
    d = emokit_create();
    k = emokit_get_count(d, EMOKIT_VID, EMOKIT_PID);
    printf("Current epoc devices connected: %d\n", k);
    status=-1;
    if ( k>0 ) {
        for ( i=k-1; i>=0 & i<k; i--) {
            status = emokit_open(d, EMOKIT_VID, EMOKIT_PID, i);
            if(status == 0 ) {
                printf("Connected : %d:%d\n",i,status);
                break;
            } else {
                printf("CANNOT CONNECT: %d:%d\n", i,status);
            }
        }
    }
    if ( status != 0 ) {
        printf("Could not connect to any device\nDo you have permission to read from : /dev/hidrawX\nsee https://github.com/openyou/emokit/issues/89\n");
        return 1;
    }

    //-------------------------------------------------------------------------------
    /* allocate the elements that will be used in the buffer communication */
    request.def = malloc(sizeof(messagedef_t));
    request.buf = NULL;
    request.def->version = VERSION;
    request.def->bufsize = 0;

    header.def = malloc(sizeof(headerdef_t));
    header.buf = NULL; /* header buf contains the channel names */
    //header.buf = labels;

    /* define the header */
    header.def->nchans    = nchans;
    header.def->nsamples  = 0;
    header.def->nevents   = 0;
    header.def->fsample   = fsample;
    header.def->data_type = DATATYPE_EMOKIT;
    header.def->bufsize   = 0;

    //-------------------------------------------------------------------------------
    /* define the stuff for the channel names */
    /* compute the size of the channel names set */
    channamesize=0;
    for( i=0; i<nchans; i++) {
        for ( j=0; labels[i][j]!='\0'; j++);
        j++;
        channamesize+=j;
    }
    /* allocate the memory for the channel names, and copy them into
      it */
    labelsbuf = malloc(WORDSIZE_CHAR*channamesize);
    k=0;
    for( i=0; i<nchans; i++) {
        for ( j=0; labels[i][j]!='\0'; j++,k++) {
            labelsbuf[k]=labels[i][j];
        }
        labelsbuf[k]=labels[i][j];
        k++;
    }
    chunkdef.type = FT_CHUNK_CHANNEL_NAMES;
    chunkdef.size = k;
    // add this info to the header buffer
    header.def->bufsize = append(&header.buf, header.def->bufsize, &chunkdef, sizeof(ft_chunkdef_t));
    header.def->bufsize = append(&header.buf, header.def->bufsize, labelsbuf, chunkdef.size);

    //-------------------------------------------------------------------------------
    /* initialization phase, send the header */
    request.def->command = PUT_HDR;
    request.def->bufsize = append(&request.buf, request.def->bufsize, header.def, sizeof(headerdef_t));
    request.def->bufsize = append(&request.buf, request.def->bufsize, header.buf, header.def->bufsize);

    fprintf(stderr,"emokit2ft: Attempting to open connection to buffer....");
    while ( (serverfd = open_connection(buffhost.name,buffhost.port)) < 0 ) {
        fprintf(stderr, "emokit2ft; failed to create socket. waiting\n");
        usleep(1000000);/* sleep for 1second and retry */
    }
    fprintf(stderr,"done.\nSending header...");
    status = tcprequest(serverfd, &request, &response);
    if (status) {
        fprintf(stderr, "emokit2ft: put header error = %d\n",status);
        sig_handler(-1);
    }
    fprintf(stderr, "done\n");
    free(request.buf);
    free(request.def);
    if (response->def->command != PUT_OK) {
        fprintf(stderr, "emokit2ft: error in 'put header' request.\n");
        sig_handler(-1);
    }
    FREE(response->buf);
    free(response->def);
    free(response);

    /* add a small pause between writing header + first data block */
    usleep(200000);


    //-------------------------------------------------------------------------------
    /* allocate space for the putdata request as 1 block, this contains
      [ request_def data_def data ] */
    putdatrequestsize = sizeof(messagedef_t) + sizeof(datadef_t) + WORDSIZE_EMOKIT*nchans*blocksize;
    requestbuf  = malloc(putdatrequestsize);
    /* define the constant part of the send-data request and allocate space for the variable part */
    request.def = requestbuf ;
    request.buf = request.def + 1; /* N.B. cool pointer arithemetic trick for above! */
    request.def->version = VERSION;
    request.def->command = PUT_DAT;
    request.def->bufsize = putdatrequestsize - sizeof(messagedef_t);
    /* setup the data part of the message */
    data.def            = request.buf;
    data.buf            = data.def + 1; /* N.B. cool pointer arithemetic trick for above */
    samples             = data.buf;     /* version with correct type */
    /* define the constant part of the data */
    data.def->nchans    = nchans;
    data.def->nsamples  = blocksize;
    data.def->data_type = DATATYPE_EMOKIT;
    data.def->bufsize   = WORDSIZE_EMOKIT * nchans * blocksize;

    //-------------------------------------------------------------------------------
    // Loop sending the data in blocks as it becomes available
    gettimeofday(&starttime,NULL); /* get time we started to compute delay before next sample */
    while (1) {

        //-------------------------------------------------------------------------------
        for ( si=0; si<blocksize; si++) { // get a block's worth of samples
            // wait until new data to get, 4 milliSec N.B. inter-sample ~= 8 milliSec
            while( emokit_read_data(d)<=0 ) {
                usleep(2000);
            }
            /* get the new data */
            c = emokit_get_next_frame(d);
            if ( verbose>1 ) {
                printf("%5d) %5d\t%5d\t%5d\t%5d\t%5d\t%5d\n", nsamp, c.counter, c.gyroX, c.gyroY, c.F3, c.FC6, c.P7);
                fflush(stdout);
            }
            // copy the samples into the data buffer, in the order we
            // *said* they should be
            samples[(si*nchans)+0] =c.counter;
            samples[(si*nchans)+1] =(c.AF3 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+2] =(c.F7  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+3] =(c.F3  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+4] =(c.FC5 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+5] =(c.T7  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+6] =(c.P7  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+7] =(c.O1  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+8] =(c.O2  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+9] =(c.P8  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+10]=(c.T8  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+11]=(c.FC6 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+12]=(c.F4  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+13]=(c.F8  - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+14]=(c.AF4 - eeg_zero_offset)*eeg_scale;
            samples[(si*nchans)+15]=c.gyroX;
            samples[(si*nchans)+16]=c.gyroY;
            nsamp+=1;/*nsamp; */
        }

        //-------------------------------------------------------------------------------
        /* send the data to the buffer */
        /* 0. If send data already read response to previous put-data */
        if ( nblk > 0 ) {
            if ( readresponse(serverfd,&responsedef) !=0 ||
                    responsedef.command != PUT_OK ) {
                fprintf(stderr,"emokit2ft: Error writing samples.\n");
            }
        }

        /* 1. Send the new data, but don't wait for a response */
        if ((k = bufwrite(serverfd, request.def, putdatrequestsize)) != putdatrequestsize) {
            fprintf(stderr, "write size = %d, should be %d\n", k, putdatrequestsize);
            sig_handler(-1);
        }

        /* do some logging */
        gettimeofday(&curtime,NULL);
        elapsedusec=(curtime.tv_usec + 1000000 * curtime.tv_sec) - (starttime.tv_usec + 1000000 * starttime.tv_sec);
        if ( elapsedusec / 1000000 >= printtime ) {
            fprintf(stderr,"%d %d %d %f (blk,samp,event,sec)\r",nblk,nsamp,0,elapsedusec/1000000.0);
            printtime+=10;
        }
        nblk+=1;
    } /* while(1) */

    // free all the stuff we've allocated
    free(labelsbuf);
    free(requestbuf);
}
Exemplo n.º 13
-1
void *sigmgr_thread()
{  
  sigset_t oset;
  int sig;
  int rc;
  pthread_t ppid = pthread_self();
  pthread_detach(ppid);
  while (1) {
    rc = sigwait(&bset, &sig);
    if (rc != -1) {
      sig_handler(sig);
    } else {
      printf("sigwaitinfo() return err:%d:%s\n", errno, strerror(errno));
    }
  }
}