Esempio n. 1
0
int main(int argc, char * argv[])
{
    struct arguments args;
    parse_arguments(argc, argv, &args);

    struct jpeg_compress_struct outputinfo;

    JBLOCKARRAY coef_buffers[MAX_COMPONENTS];

    FILE *output = setup_output(args.outputname, &outputinfo);

    read_DCT(args.inputname, coef_buffers, &outputinfo);

    unsigned int seed = (unsigned) strtoul(args.userPassword, NULL, 10);
    node *root;
    size_t usable_size = make_linked_list(coef_buffers, seed, &root);

    if (args.embedFlag) {
        embed(coef_buffers, args.embedMessage, root, usable_size);
        write_DCT(args.outputname, coef_buffers, &outputinfo);
    }
    else if (args.extractFlag) {
        extract(args.message_size, root, usable_size);
    }

    fclose(output);

    return 0;
}
Esempio n. 2
0
int main (int argc, char **argv) {
	setup_output(SAMPLERATE, AFMT_U8, 1, 0x00030008);
	fd_set readfds, writefds;
	for (;;) {
		FD_ZERO (&readfds);
		FD_ZERO (&writefds);
		FD_SET (1, &writefds);
		FD_SET (0, &readfds);
		switch (select(2, &readfds, &writefds, NULL, NULL)) {
			case -1: err(1, "select");
			case 0: continue;
			default:
				if (FD_ISSET(0, &readfds)) midirdy();
				if (FD_ISSET(1, &writefds)) send(nextsample()); }}
	return 0; }
Esempio n. 3
0
// Initializes channels.
//
// Parameters:
//   n_channels     the number of channels
//   in_format      the input format code
//   out_format     the output format code
//   sampling_rate  the sampling rate
//   apply_dither   true to apply dither to output
//
// Returns:
//    0 if successful
//   -1 if channel limit is exceeded
int
brutefir::init_channels(int n_channels,
                        int in_format,
                        int out_format,
                        int sampling_rate,
                        bool apply_dither)
{
    int n;

    if (n_channels > BF_MAXCHANNELS)
    {
        pinfo("Number of channels (%u) exceeds limit (%u).", n_channels, BF_MAXCHANNELS);
        return -1;
    }

    bfconf->sampling_rate = sampling_rate;
    bfconf->n_channels = n_channels;

    // setup inputs and outputs
    for (n = 0; n < bfconf->n_channels; n++)
    {
        setup_input(n, in_format);
        setup_output(n, out_format, apply_dither);
    }

    // initialize overflow structure
    memset(overflow, 0, sizeof(struct bfoverflow_t) * bfconf->n_channels);
    memset(last_overflow, 0, sizeof(struct bfoverflow_t) * bfconf->n_channels);

    for (n = 0; n < bfconf->n_channels; n++)
    {
        if (bfconf->outputs[n].bf.sf.isfloat)
        {
            overflow[n].max = 1.0;
            last_overflow[n].max = 1.0;
        }
        else
        {
            overflow[n].max = get_max(bfconf->outputs[n].bf.sf.bytes);
            last_overflow[n].max = get_max(bfconf->outputs[n].bf.sf.bytes);
        }
    }

    return 0;
}
Esempio n. 4
0
/*
 * Performs the exec argument processing, all  of the child forking and
 * execing, and child cleanup.
 * Sets exitcode to non-zero if any errors occurred.
 */
void
do_mounts(void)
{
	int 		i, isave, cnt;
	vfsent_t 	*vp, *vpprev, **vl;
	char		*newargv[ARGV_MAX];
	pid_t		child;

	/*
	 * create the arg list once;  the only differences among
	 * the calls are the options, special and mountp fields.
	 */
	i = 2;
	if (cflg)
		newargv[i++] = "-c";
	if (gflg)
		newargv[i++] = "-g";
	if (mflg)
		newargv[i++] = "-m";
	if (Oflg)
		newargv[i++] = "-O";
	if (qflg)
		newargv[i++] = "-q";
	if (rflg)
		newargv[i++] = "-r";
	if (dashflg)
		newargv[i++] = "--";
	if (oflg) {
		newargv[i++] = "-o";
		newargv[i++] = specific_opts;
	}
	isave = i;

	/*
	 * Main loop for the mount processes
	 */
	vl = vfsarray;
	cnt = vfsarraysize;
	for (vpprev = *vl; vp = *vl; vpprev = vp, vl++, cnt--) {
		/*
		 * Check to see if we cross a mount level: e.g.,
		 * /a/b -> /a/b/c.  If so, we need to wait for all current
		 * mounts to finish, rerun realpath on the remaining mount
		 * points, and resort the list.
		 *
		 * Also, we mount serially as long as there are lofs's
		 * to mount to avoid improper mount ordering.
		 */
		if (vp->mlevel > vpprev->mlevel || lofscnt > 0) {
			vfsent_t **vlp;

			while (nrun > 0 && (dowait() != -1))
				;
			/*
			 * Gads! It's possible for real path mounts points to
			 * change after mounts are done at a lower mount
			 * level.
			 * Thus, we need to recalculate mount levels and
			 * resort the list from this point.
			 */
			for (vlp = vl; *vlp; vlp++)
				(void) setrpath(*vlp);
			/*
			 * Sort the remaining entries based on their newly
			 * resolved path names.
			 * Do not sort if we still have lofs's to mount.
			 */
			if (lofscnt == 0) {
				qsort((void *)vl, cnt, sizeof (vfsent_t *),
				    mlevelcmp);
				vp = *vl;
			}
		}

		if (vp->flag & VRPFAILED) {
			fprintf(stderr, gettext(
			    "%s: Nonexistent mount point: %s\n"),
			    myname, vp->v.vfs_mountp);
			vp->flag |= VNOTMOUNTED;
			exitcode = 1;
			continue;
		}

		/*
		 * If mount options were not specified on the command
		 * line, then use the ones found in the vfstab entry,
		 * if any.
		 */
		i = isave;
		if (!oflg && vp->v.vfs_mntopts) {
			newargv[i++] = "-o";
			newargv[i++] = vp->v.vfs_mntopts;
		}
		newargv[i++] = vp->v.vfs_special;
		newargv[i++] = vp->rpath;
		newargv[i] = NULL;

		/*
		 * This should never really fail.
		 */
		while (setup_iopipe(vp) == -1 && (dowait() != -1))
			;

		while (nrun >= maxrun && (dowait() != -1))	/* throttle */
			;

		if ((child = fork()) == -1) {
			perror("fork");
			cleanup(-1);
			/* not reached */
		}
		if (child == 0) {		/* child */
			signal(SIGHUP, SIG_IGN);
			signal(SIGQUIT, SIG_IGN);
			signal(SIGINT, SIG_IGN);
			setup_output(vp);
			doexec(vp->v.vfs_fstype, newargv);
			perror("exec");
			exit(1);
		}

		/* parent */
		(void) close(vp->sopipe[WRPIPE]);
		(void) close(vp->sepipe[WRPIPE]);
		vp->pid = child;
		nrun++;
	}
	/*
	 * Mostly done by now - wait and clean up the stragglers.
	 */
	cleanup(0);
}
Esempio n. 5
0
int main(int argc, char **argv)
{
    int err;
    int has_set_log_format = 0;
    int is_clear_log = 0;
    int getLogSize = 0;
    int mode = O_RDONLY;
	int i;
//    const char *forceFilters = NULL;
	struct log_device_t* devices = NULL;
	struct log_device_t* dev;

    g_logformat = (log_format *)log_format_new();

    if (argc == 2 && 0 == strcmp(argv[1], "--test")) {
        logprint_run_tests();
        exit(0);
    }

    if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
        show_help(argv[0]);
        exit(0);
    }

    for (;;) {
        int ret;

        ret = getopt(argc, argv, "cdt:gsf:r:n:v:b:D");

        if (ret < 0) {
            break;
        }

        switch(ret) {
            case 's':
                // default to all silent
                log_add_filter_rule(g_logformat, "*:s");
            break;

            case 'c':
                is_clear_log = 1;
                mode = O_WRONLY;
            break;

            case 'd':
                g_nonblock = true;
            break;

            case 't':
                g_nonblock = true;
                g_tail_lines = atoi(optarg);
            break;


            case 'g':
                getLogSize = 1;
            break;

			case 'b': {
						  char* buf = (char*) malloc(strlen(LOG_FILE_DIR) + strlen(optarg) + 1);
						  if (buf == NULL) {
							  fprintf(stderr,"Can't malloc LOG_FILE_DIR\n");
							  exit(-1);
						  }
						  strcpy(buf, LOG_FILE_DIR);
						  strcat(buf, optarg);
						  //		snprintf(buf, strlen(LOG_FILE_DIR) + strlen(optarg) + 1, "%s%s", LOG_FILE_DIR, optarg);

                if (devices) {
					dev = devices;
                    while (dev->next) {
						dev = dev->next;
					}
					dev->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
					if (dev->next == NULL) {
						fprintf(stderr,"Can't malloc log_device\n");
						exit(-1);
					}
					dev->next->device = buf;
					dev->next->fd = -1;
					dev->next->printed = false;
					dev->next->queue = NULL;
					dev->next->next = NULL;

                } else {
					devices = (struct log_device_t *)malloc( sizeof(struct log_device_t));
					if (devices == NULL) {
						fprintf(stderr,"Can't malloc log_device\n");
						exit(-1);
					}
					devices->device = buf;
					devices->fd = -1;
					devices->printed = false;
					devices->queue = NULL;
					devices->next = NULL;
                }
                g_dev_count++;
            }
            break;

            case 'f':
                // redirect output to a file

                g_output_filename = optarg;

            break;

            case 'r':
//                if (optarg == NULL) {
//					fprintf(stderr,"optarg == null\n");
 //                  g_log_rotate_size_kbytes = DEFAULT_LOG_ROTATE_SIZE_KBYTES;
 //              } else {
                    //long logRotateSize;
                    //char *lastDigit;

                    if (!isdigit(optarg[0])) {
                        fprintf(stderr,"Invalid parameter to -r\n");
                        show_help(argv[0]);
                        exit(-1);
                    }
                    g_log_rotate_size_kbytes = atoi(optarg);
   //             }
            break;

            case 'n':
                if (!isdigit(optarg[0])) {
                    fprintf(stderr,"Invalid parameter to -r\n");
                    show_help(argv[0]);
                    exit(-1);
                }

                g_max_rotated_logs = atoi(optarg);
            break;

            case 'v':
                err = set_log_format (optarg);
                if (err < 0) {
                    fprintf(stderr,"Invalid parameter to -v\n");
                    show_help(argv[0]);
                    exit(-1);
                }

                has_set_log_format = 1;
            break;

			default:
				fprintf(stderr,"Unrecognized Option\n");
				show_help(argv[0]);
				exit(-1);
			break;
		}
	}

	if (!devices) {
        devices = (struct log_device_t *)malloc( sizeof(struct log_device_t));
		if (devices == NULL) {
			fprintf(stderr,"Can't malloc log_device\n");
			exit(-1);
		}
		devices->device = strdup("/dev/"LOGGER_LOG_MAIN);
		devices->fd = -1;
		devices->printed = false;
		devices->queue = NULL;
		devices->next = NULL;
        g_dev_count = 1;


        int accessmode =
                  (mode & O_RDONLY) ? R_OK : 0
                | (mode & O_WRONLY) ? W_OK : 0;

        // only add this if it's available
	if (0 == access("/dev/"LOGGER_LOG_SYSTEM, accessmode)) {
		devices->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
		if (devices->next == NULL) {
			fprintf(stderr,"Can't malloc log_device\n");
			exit(-1);
		}
		devices->next->device = strdup("/dev/"LOGGER_LOG_SYSTEM);
		devices->next->fd = -1;
		devices->next->printed = false;
		devices->next->queue = NULL;
		devices->next->next = NULL;
		g_dev_count ++;
	}
	if (0 == access("/dev/"LOGGER_LOG_APPS, accessmode)) {
		devices->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
		if (devices->next == NULL) {
			fprintf(stderr,"Can't malloc log_device\n");
			exit(-1);
		}
		devices->next->device = strdup("/dev/"LOGGER_LOG_APPS);
		devices->next->fd = -1;
		devices->next->printed = false;
		devices->next->queue = NULL;
		devices->next->next = NULL;
		g_dev_count ++;
	}
/*
        // only add this if it's available
	int fd;
	if ((fd = open("/dev/"LOGGER_LOG_SYSTEM, mode)) != -1) {
		devices->next = (struct log_device_t *)malloc( sizeof(struct log_device_t));
		devices->next->device = strdup("/dev/"LOGGER_LOG_SYSTEM);
		devices->next->fd = -1;
		devices->next->printed = false;
		devices->next->queue = NULL;
		devices->next->next = NULL;
		g_dev_count ++;

		close(fd);
        }
*/
    }

    if (g_log_rotate_size_kbytes != 0 && g_output_filename == NULL)
	{
		fprintf(stderr,"-r requires -f as well\n");
		show_help(argv[0]);
		exit(-1);
	}

    setup_output();


	if (has_set_log_format == 0) {
		err = set_log_format("brief");
	}
/*
		const char* logFormat = getenv("DLOG_PRINTF_LOG");

	        if (logFormat != NULL) {
			err = set_log_format("brief");

			if (err < 0) {
				fprintf(stderr, "invalid format in DLOG_PRINTF_LOG '%s'\n", logFormat);
			}
		}
	}
	if (forceFilters) {
		err = log_add_filter_string(g_logformat, forceFilters);
		if (err < 0) {
			fprintf (stderr, "Invalid filter expression in -logcat option\n");
			exit(0);
		}
	} else if (argc == optind) {
        // Add from environment variable
		char *env_tags_orig = getenv("DLOG_LOG_TAGS");

		if (env_tags_orig != NULL) {
			err = log_add_filter_string(g_logformat, env_tags_orig);

			if (err < 0) {
				fprintf(stderr, "Invalid filter expression in DLOG_LOG_TAGS\n");
				show_help(argv[0]);
				exit(-1);
			}
		}
	} else {
        // Add from commandline
*/
	fprintf(stderr,"arc = %d, optind = %d ,Kb %d, rotate %d\n", argc, optind,g_log_rotate_size_kbytes,g_max_rotated_logs);

	if(argc == optind )
	{
		// Add from environment variable
        //char *env_tags_orig = getenv("DLOG_TAGS");
		log_add_filter_string(g_logformat, "*:d");
	}
	else
	{

		for (i = optind ; i < argc ; i++) {
			err = log_add_filter_string(g_logformat, argv[i]);

			if (err < 0) {
				fprintf (stderr, "Invalid filter expression '%s'\n", argv[i]);
				show_help(argv[0]);
				exit(-1);
			}
		}
	}
/*
    }
*/
    dev = devices;
    while (dev) {
        dev->fd = open(dev->device, mode);
        if (dev->fd < 0) {
            fprintf(stderr, "Unable to open log device '%s': %s\n",
                dev->device, strerror(errno));
            exit(EXIT_FAILURE);
        }

        if (is_clear_log) {
            int ret;
            ret = clear_log(dev->fd);
            if (ret) {
                perror("ioctl");
                exit(EXIT_FAILURE);
            }
        }

        if (getLogSize) {
            int size, readable;

            size = get_log_size(dev->fd);
            if (size < 0) {
                perror("ioctl");
                exit(EXIT_FAILURE);
            }

            readable = get_log_readable_size(dev->fd);
            if (readable < 0) {
                perror("ioctl");
                exit(EXIT_FAILURE);
            }

            printf("%s: ring buffer is %dKb (%dKb consumed), "
                   "max entry is %db, max payload is %db\n", dev->device,
                   size / 1024, readable / 1024,
                   (int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
        }

        dev = dev->next;
    }

    if (getLogSize) {
        return 0;
    }

    if (is_clear_log) {
        return 0;
    }

    read_log_lines(devices);

    return 0;
}
Esempio n. 6
0
File: main.cpp Progetto: DPMI/marcd
int main(int argc, char *argv[]){
	/* extract program name from path. e.g. /path/to/MArCd -> MArCd */
	const char* separator = strrchr(argv[0], '/');
	if ( separator ){
		program_name = separator + 1;
	} else {
		program_name = argv[0];
	}

	default_env();

	int ret;
	int option_index = 0;
	int op;

#ifdef HAVE_INIPARSER_H
	if ( config::load(argc, argv) != 0 ){ /* passing argv so it can read -f/--config */
		return 1; /* error already shown */
	}
#endif

	while ( (op = getopt_long(argc, argv, shortopts, longopts, &option_index)) != -1 ){
		switch (op){
		case '?': /* error */
			exit(1);

		case 0: /* long opt */
			break;

		case 'b': /* --daemon */
			daemon_mode = 1;
			break;

		case 's': /* --syslog */
			syslog_flag = true;
			break;

		case FLAG_USER: /* --user */
			config::set_drop_username(optarg);
			break;

		case FLAG_GROUP: /* --group */
			config::set_drop_group(optarg);
			break;

		case FLAG_DROP_PRIV: /** --drop */
			drop_priv_flag = true;
			break;

		case FLAG_NODROP_PRIV: /** --no-drop */
			drop_priv_flag = false;
			break;

		case 'f':
#ifndef HAVE_INIPARSER_H
			fprintf(stderr, "%s: configuration files not supported (build with --with-iniparser)\n", program_name);
#endif
			break;

		case 'H':
			strncpy(db_hostname, optarg, sizeof(db_hostname));
			db_hostname[sizeof(db_hostname)-1] = '\0';
			break;

		case 'N':
			strncpy(db_name, optarg, sizeof(db_name));
			db_name[sizeof(db_name)-1] = '\0';
			break;

		case 'u':
			strncpy(db_username, optarg, sizeof(db_username));
			db_username[sizeof(db_username)-1] = '\0';
			break;

		case 'p':
			if ( strcmp(optarg, "-") == 0 ){ /* read password from stdin */
				strncpy(db_password, getpass("mysql password: "******"Invalid port given to --relay: %s. Ignored\n", optarg);
				}
			}

			break;

		case FLAG_DATADIR:
			free(rrdpath);
			rrdpath = strdup(optarg);
			break;

		case FLAG_PIDFILE:
			pidfile = optarg;
			break;

		case 'v': /* --verbose */
			verbose_flag = 1;
			break;

		case 'q': /* --quiet */
			verbose_flag = 0;
			break;

		case 'd': /* --debug */
			debug_flag = 1;
			break;

		case 'h': /* --help */
			show_usage();
			exit(0);

		default:
			if ( option_index >= 0 ){
				fprintf(stderr, "flag --%s declared but not handled\n", longopts[option_index].name);
			} else {
				fprintf(stderr, "flag -%c declared but not handled\n", op);
			}
			abort();
		}
	}

	/* database */
	if ( argc > optind ){
		strncpy(db_name, argv[optind], sizeof(db_name));
		db_name[sizeof(db_name)-1] = '\0';
	}

	setup_output();

	/* test if possible to drop privileges */
	if ( drop_priv_flag && getuid() != 0 ){
		Log::message(MAIN, "Not executing as uid=0, cannot drop privileges.\n");
		drop_priv_flag = 0;
	}

	/* Drop privileges.
	 * Done before forking since unlinking requires write permission to folder so
	 * if it fails to write it will fail unlinking. It is also done before
	 * check_env so it actually check environment for the dropped user instead of
	 * root.
	 */
	if ( drop_priv_flag ){
		privilege_drop();
	}

	/* sanity checks */
	show_env();
	if ( !check_env() ){
		return 1;
	}

	if ( daemon_mode ){
		/* opening file before fork since it will be a fatal error if it fails to write the pid */
		FILE* fp = fopen(pidfile, "w");
		if ( !fp ){
			Log::fatal(MAIN, "failed to open '%s` for writing: %s\n", pidfile, strerror(errno));
			return 1;
		}

		Log::message(MAIN, "Forking to background\n");
		pid_t pid = fork();

		if ( pid ){ /* parent */
			fprintf(fp, "%d\n", pid);
			fclose(fp);

			/* change owner of pidfile */
			if ( drop_priv_flag ){
				if ( chown(pidfile, drop_uid, drop_gid) != 0 ){
					Log::error("failed to change owner of '%s`, will probably fail to unlink it later: %s\n", pidfile, strerror(errno));
				}
			}

			return 0;
		}

		fclose(fp);
	}

	/* initialize daemons */
	pthread_barrier_t barrier;
	int threads = 1;
	threads += (int)have_control_daemon;
	threads += (int)have_relay_daemon;
	pthread_barrier_init(&barrier, NULL, threads);
	control.addr = relay.addr;

	if ( have_control_daemon && (ret=Daemon::instantiate<Control>(2000, &barrier)) != 0 ){
		Log::fatal(MAIN, "Failed to initialize control daemon, terminating.\n");
		if ( daemon_mode && unlink(pidfile) == -1 ){
			Log::fatal(MAIN, "Failed to remove pidfile: %s\n", strerror(errno));
		}
		return ret;
	}

	if ( have_relay_daemon && (ret=Daemon::instantiate<Relay>(2000, &barrier)) != 0 ){
		Log::fatal(MAIN, "Failed to initialize relay daemon, terminating.\n");
		if ( daemon_mode && unlink(pidfile) == -1 ){
			Log::fatal(MAIN, "Failed to remove pidfile: %s\n", strerror(errno));
		}
		return ret;
	}

	/* install signal handler */
	signal(SIGINT, handle_signal);
	signal(SIGTERM, handle_signal);

	/* release all threads and wait for them to finish*/
	pthread_barrier_wait(&barrier);
	if ( daemon_mode ){
		Log::message(MAIN, "Threads started. Going to sleep.\n");
	} else {
		Log::message(MAIN, "Threads started. Going to sleep. Abort with SIGINT\n");
	}
	Daemon::join_all();

	/* cleanup */
	free(rrdpath);
	if ( daemon_mode && unlink(pidfile) == -1 ){
		Log::fatal(MAIN, "Failed to remove pidfile: %s\n", strerror(errno));
	}

	Log::message(MAIN, "%s terminated.\n", program_name);
	return 0;
}
Esempio n. 7
0
/**
 * Parse command line options.
 *
 * @param argv program arguments
 */
void read_options(int argc, char *argv[])
{
	struct parsed_cmd_line_t cmd_line;
#ifdef _WIN32
	int i;
	vector_t *expanded_cnames;
#endif

	memset(&opt, 0, sizeof(opt));
	opt.mem = rsh_vector_new_simple();
	opt.find_max_depth = -1;

	/* initialize cmd_line */
	memset(&cmd_line, 0, sizeof(cmd_line));
	rsh_blocks_vector_init(&cmd_line.options);
	cmd_line.argv = argv;
	cmd_line.argc = argc;

	/* parse command line and apply encoding options */
	parse_cmdline_options(&cmd_line);
	read_config();
	
#ifdef _WIN32
	/* set default encoding if no encoding options were specified, */
	/* this should be done here, even if config file was not found. */
	if( (opt.flags & OPT_ENCODING) == 0 ) opt.flags |= OPT_UTF8;
#endif

	/* note: encoding and -o/-l options are already applied */
	IF_WINDOWS(setup_console());
	setup_output(); /* setup program output */

	apply_cmdline_options(&cmd_line); /* process the rest of command options */

	/* options were processed, so we don't need them anymore */
	rsh_blocks_vector_destroy(&cmd_line.options);
	
#ifdef _WIN32
	expanded_cnames = rsh_vector_new_simple();

	/* convert paths to internal encoding and expand wildcards. */
	for(i = 0; i < cmd_line.n_files; i++) {
		wchar_t* path = cmd_line.files[i];
		wchar_t* p = wcschr(path, L'\0') - 1;

		/* strip trailing '\','/' symbols (if not preceded by ':') */
		for(; p > path && IS_PATH_SEPARATOR_W(*p) && p[-1] != L':'; p--) *p = 0;
		expand_wildcards(expanded_cnames, path);
	}

	opt.cmd_vec = expanded_cnames;
	opt.files = (char**)expanded_cnames->array;
	opt.n_files = (int)expanded_cnames->size;
	free(cmd_line.files);
	LocalFree(cmd_line.warg);
#else
	opt.files = cmd_line.files;
	opt.n_files = cmd_line.n_files;
	rsh_vector_add_ptr(opt.mem, opt.files);
#endif

	make_final_options_checks();

	set_default_sums_flags(argv[0]); /* detect default hashes from program name */
}
Esempio n. 8
0
inline
pid_t
posix_start(const Executable& exe,
            const Arguments& args,
            const environment& env,
            info_map& infoin,
            info_map& infoout,
            const posix_setup& setup)
{
    pid_t pid = ::fork();
    if (pid == -1) {
        boost::throw_exception
            (system_error("boost::process::detail::posix_start",
                          "fork(2) failed", errno));
    } else if (pid == 0) {
#if defined(F_MAXFD)
        int maxdescs = std::max(::fcntl(0, F_MAXFD), 128); // XXX
#else
        int maxdescs = 128; // XXX
#endif
        try {
            boost::scoped_array< bool > closeflags(new bool[maxdescs]);
            for (int i = 0; i < maxdescs; i++)
                closeflags.get()[i] = true;

            setup_input(infoin, closeflags.get(), maxdescs);
            setup_output(infoout, closeflags.get(), maxdescs);

            for (int i = 0; i < maxdescs; i++)
                if (closeflags.get()[i])
                    ::close(i);

            setup();
        } catch (const system_error& e) {
            ::write(STDERR_FILENO, e.what(), std::strlen(e.what()));
            ::write(STDERR_FILENO, "\n", 1);
            ::exit(EXIT_FAILURE);
        }

        std::pair< std::size_t, char** > argcv =
            collection_to_posix_argv(args);
        char** envp = environment_to_envp(env);
        ::execve(exe.c_str(), argcv.second, envp);
        system_error e("boost::process::detail::posix_start",
                       "execve(2) failed", errno);

        for (std::size_t i = 0; i < argcv.first; i++)
            delete [] argcv.second[i];
        delete [] argcv.second;

        for (std::size_t i = 0; i < env.size(); i++)
            delete [] envp[i];
        delete [] envp;

        ::write(STDERR_FILENO, e.what(), std::strlen(e.what()));
        ::write(STDERR_FILENO, "\n", 1);
        ::exit(EXIT_FAILURE);
    }

    BOOST_ASSERT(pid > 0);

    for (info_map::iterator iter = infoin.begin();
         iter != infoin.end(); iter++) {
        stream_info& si = (*iter).second;

        if (si.m_type == stream_info::use_pipe)
            si.m_pipe->rend().close();
    }

    for (info_map::iterator iter = infoout.begin();
         iter != infoout.end(); iter++) {
        stream_info& si = (*iter).second;

        if (si.m_type == stream_info::use_pipe)
            si.m_pipe->wend().close();
    }

    return pid;
}
Esempio n. 9
0
void
setup(int pid)
{
    struct perf_event_attr hw;
    struct timeval tv;
    int ret;

    memset(&hw, 0, sizeof(hw));
    hw.type = PERF_TYPE_RAW;
    hw.size = sizeof(hw);
    hw.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
        PERF_FORMAT_TOTAL_TIME_RUNNING;
    //hw.inherit = 1;
    //hw.enable_on_exec = 1;
    //hw.disabled = 1;

    gbl.ncpus = sysconf(_SC_NPROCESSORS_ONLN);
    gbl.ncores = gbl.ncpus / 4;
    events = (evinfo (*)[NEVENTS])malloc(gbl.ncpus * NEVENTS * sizeof(struct evinfo));
    if (events == NULL)
        err(1, "Can't malloc events");
    threads = (pthread_t *)malloc(gbl.ncpus*sizeof(pthread_t));
    if (threads == NULL)
        err(1, "Can't malloc threads");
    memset(events, 0, gbl.ncpus*NEVENTS*sizeof(struct evinfo));
    counters = (counter *)_mm_malloc(gbl.ncpus * sizeof(struct counter), 64);
    if (counters == NULL)
        err(1, "Can't malloc counters");
    memset(counters, 0, gbl.ncpus * sizeof(struct counter));
    lastctr = (counter *)_mm_malloc(gbl.ncpus * sizeof(struct counter), 64);
    if (lastctr == NULL)
        err(1, "Can't malloc lastctr");
    memset(lastctr, 0, gbl.ncpus * sizeof(struct counter));
    /* Could do this per thread */
    for (int cpu = 0; cpu < gbl.ncpus; ++cpu)
        for (int i = 0; i < NEVENTS; ++i)
        {
            evinfo *ep = &events[cpu][i];
            hw.config = evtcodes[i];
            // We'd like to use pid instead of -1 here, but apparently
            // broken on KNC 2.6.38
            ep->fd = perf_event_open(&hw, -1, cpu, -1, 0);
            if (ep->fd == -1)
                err(1, "CPU %d, event 0x%lx", cpu, hw.config);
#if 0
            // We'd like to use user-mode rdpmc pattern but need
            // newer kernel that exports even non-running counters
            ep->buf = mmap(NULL, 2*4096, PROT_READ|PROT_WRITE, MAP_SHARED,
                ep->fd, 0);
            if (ep->buf == MAP_FAILED)
                err(1, "CPU %d, event 0x%lx: cannot mmap buffer",
                    cpu, hw.config);
#endif
        }

    pthread_barrier_init(&barrier, NULL, gbl.ncpus);
    /* Now spawn a pthread on every processor */
    for (int i = 1; i < gbl.ncpus; ++i)
    {
        pthread_attr_t attr;
        cpu_set_t cpuset;
        CPU_ZERO(&cpuset);
        CPU_SET(i, &cpuset);
        pthread_attr_init(&attr);
        pthread_attr_setaffinity_np(&attr, sizeof(cpuset), &cpuset);
        ret = pthread_create(&threads[i], &attr, thrstart, (void *)i);
        if (ret)
            err(1, "pthread_create returns %d", ret);
        pthread_attr_destroy(&attr);
    }
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(0, &cpuset);
    sched_setaffinity(0, sizeof(cpuset), &cpuset);

    setup_output();
    ret = gettimeofday(&tv, 0);
    if (ret != 0)
        err(1, "gettimeofday");
    starttime = tv.tv_sec + (double)tv.tv_usec * 1e-6;
    //pthread_barrier_wait(&barrier);
}
Esempio n. 10
0
void *Read_CT_Data(void *arg)
{
    rp_pinState_t heart_beat_state; 
    uint32_t buff_size = RP_BUF_SIZE;
    uint32_t trig_pos;
    float *buff_ch1 = (float *)malloc(buff_size * sizeof(float));
    float *buff_ch2 = (float *)malloc(buff_size * sizeof(float));
    float val_sum_ch1,val_sum_ch2,val_ch1,val_ch2;
    float tmp_val_ch1, tmp_val_ch2;
    float charge_ch1;
    float charge_ch2;  
    int counter;
    clock_t start_time, diff;
    int msec;
    int endpoints;
    int startpoints;
    
    val_sum_ch1=0;
    counter=0;
    msec=0;
    new_data=0;
    
    /* Print error, if rp_Init() function failed */
    if(rp_Init() != RP_OK)
    {
        fprintf(stderr, "Rp api init failed!n");
    }
    
    setup_output();

    //rp_AcqSetDecimation(RP_DEC_8 );
    rp_AcqSetSamplingRate(RP_SMP_125M);
    //rp_AcqSetSamplingRate(RP_SMP_15_625M);
    rp_AcqSetTriggerLevel(trig_level); //Trig level is set in Volts while in SCPI is set in mV
    rp_AcqSetTriggerDelayNs(0);
    //rp_AcqSetTriggerDelay(0);
    rp_AcqSetAveraging(true);
    rp_AcqStart();

    //rp_AcqSetTriggerSrc(RP_TRIG_SRC_EXT_PE);
    //rp_AcqSetTriggerSrc(RP_TRIG_SRC_CHA_NE);			// Trig on signal
    rp_AcqSetTriggerSrc(trig_source);			
    rp_acq_trig_state_t state = RP_TRIG_STATE_TRIGGERED;

    // Get clock
    start_time = clock();

    rp_DpinSetDirection ( RP_LED4, RP_OUT);
    rp_DpinSetDirection ( RP_LED3, RP_OUT);
    rp_DpinSetDirection ( RP_DIO1_P, RP_OUT);
    rp_AcqStart();    
    //Clear count_table
    count_table[0]=0;
    free_counter=0;
    heart_beat_state=RP_LOW;

	while(1)
	{
	    // Wait for trig
	    
	    while(1)
	    {
		diff=clock()-start_time;
		msec=diff*1000/CLOCKS_PER_SEC;
		rp_AcqGetTriggerState(&state);
		if(state == RP_TRIG_STATE_TRIGGERED)
		{
		    usleep(10);
		    triggered=1;
		    break;
		}
		if (msec>2000)
		{
		    rp_AcqStart();
		    rp_AcqSetTriggerSrc(trig_source);
		    rp_GenAmp(RP_CH_2, 0);
		    triggered=0;
		    printf("No trig for 2 s... Set output analog output to zero");
		}

	    }
	    // Get data
	    rp_DpinSetState( RP_LED4, RP_HIGH);
	    rp_AcqGetWritePointerAtTrig(&trig_pos);
	    //printf("Trig pos: %d", trig_pos);
	    // Check if trig_pos is too close to buffer start/end
	    if ((trig_pos+num_data_points_after_trig)>(RP_BUF_SIZE-1))
	    {
		endpoints=(RP_BUF_SIZE-1)-(trig_pos-num_data_points_before_trig);
		startpoints=num_data_points_after_trig-((RP_BUF_SIZE-1)-trig_pos);
		rp_AcqGetDataPosV(RP_CH_1,0,(RP_BUF_SIZE-1),buff_ch1,&buff_size);			// Get entire buffer 
		rp_AcqGetDataPosV(RP_CH_2,0,(RP_BUF_SIZE-1),buff_ch2,&buff_size);			// Get entire buffer

		val_ch1=integrated_charge(buff_ch1,((RP_BUF_SIZE-1)-endpoints),(RP_BUF_SIZE-1));
		tmp_val_ch1=integrated_charge(buff_ch1,0,startpoints);
		val_ch2=integrated_charge(buff_ch2,((RP_BUF_SIZE-1)-endpoints),(RP_BUF_SIZE-1));
		tmp_val_ch2=integrated_charge(buff_ch2,0,startpoints);
		val_ch1=val_ch1+tmp_val_ch1;
		val_ch2=val_ch2+tmp_val_ch2;
	
		//Debug
		//printf("High Ring Buffer overflow\n");
		//printf("ch1: %f ch2: %f\n",val_ch1,val_ch2);
		//printf("Trig pos: %d end %d start %d\n", trig_pos, endpoints, startpoints);
		
	    }
	    else if ((trig_pos-num_data_points_before_trig)<0)
	    {	
		
		endpoints=(trig_pos-num_data_points_before_trig);
		startpoints=num_data_points_after_trig-endpoints;
		rp_AcqGetDataPosV(RP_CH_1,0,(RP_BUF_SIZE-1),buff_ch1,&buff_size);			// Get entire buffer
		rp_AcqGetDataPosV(RP_CH_2,0,(RP_BUF_SIZE-1),buff_ch2,&buff_size);			// Get entire buffer

		val_ch1=integrated_charge(buff_ch1,((RP_BUF_SIZE-1)-endpoints),(RP_BUF_SIZE-1));
		tmp_val_ch1=integrated_charge(buff_ch1,0,startpoints);
		val_ch2=integrated_charge(buff_ch2,((RP_BUF_SIZE-1)-endpoints),(RP_BUF_SIZE-1));
		tmp_val_ch2=integrated_charge(buff_ch2,0,startpoints);
		val_ch1=val_ch1+tmp_val_ch1;
		val_ch2=val_ch2+tmp_val_ch2;
	
		//Debug
		printf("Low Ring Buffer underrun\n");
		printf("ch1: %f ch2: %f\n",val_ch1,val_ch2);
		printf("Trig pos: %d end %d start %d\n", trig_pos, endpoints, startpoints);
	    }
	    else
	    {
		rp_AcqGetDataPosV(RP_CH_1,(trig_pos-num_data_points_before_trig),(trig_pos+num_data_points_after_trig),buff_ch1,&buff_size);
		rp_AcqGetDataPosV(RP_CH_2,(trig_pos-num_data_points_before_trig),(trig_pos+num_data_points_after_trig),buff_ch2,&buff_size);
		val_ch1=integrated_charge(buff_ch1,0,(num_data_points_after_trig+num_data_points_before_trig));
		val_ch2=integrated_charge(buff_ch2,0,(num_data_points_after_trig+num_data_points_before_trig));
	    }
	        
	    val_sum_ch1=val_sum_ch1+val_ch1;
	    val_sum_ch2=val_sum_ch2+val_ch2;
	    counter++;
	    charge[0]=val_ch1+val_ch2;

	    //rp_DpinSetState( RP_DIO1_P, RP_HIGH);
	    //usleep(20);
	    //rp_DpinSetState( RP_DIO1_P, RP_LOW);
	    
	    // Update data each s, 1050 ms to make sure the buffers update even @ 1 Hz trigger rate
	    if (msec>1050)
	    {
		start_time = clock();
		charge_ch1=(val_sum_ch1/(counter-1));
		charge_ch2=(val_sum_ch2/(counter-1));
		pthread_mutex_lock( &mutex1 );
		charge[1]=charge_ch1+charge_ch2;
		// Update table of volt & counters for sec 1-9
		for (int i=9;i>1;i--)
		{
		   count_table[i]=count_table[i-1]+counter;
		   charge[i]=charge[i-1]+charge[1];
		}
		count_table[1]=counter;
		charge[1]=charge[1];
		printf("\nNo of Triggers: %d, Time betweem (msec): %d\n", count_table[1], msec);

		/* Generating amplitude */
		//Check if overflow for the DAC
		if (charge[1]<1)
		{
		    rp_GenAmp(RP_CH_2, charge[1]);
		}
		else
		{
		    rp_GenAmp(RP_CH_2, 1);
		}

		printf("Charge: %f nC, Charge Ch1: %f nC, Charge Ch2: %f nC\n",charge[1], charge_ch1,charge_ch2);
		fflush(stdout);
		val_sum_ch1=0;
		val_sum_ch2=0;
		counter=0;
		free_counter++;
		// Digital output heartbeat
		rp_DpinGetState(RP_DIO1_P, &heart_beat_state);
		if (heart_beat_state==RP_LOW)
		{
		    rp_DpinSetState( RP_DIO1_P, RP_HIGH);
		}
		else
		{
		    rp_DpinSetState( RP_DIO1_P, RP_LOW);  
		}
		// Get FPGA temp
		rp_HealthGetValue(RP_TEMP_FPGA, &fpga_temp);
		printf("FPGA temp: %.01f C\n",fpga_temp);
		
		
	    }
	    new_data=1;
	    pthread_mutex_unlock( &mutex1 );
	    rp_AcqStart();
	    rp_AcqSetTriggerSrc(trig_source);
	    rp_DpinSetState( RP_LED4, RP_LOW);
	    
	    
	}
	/* Releasing resources */

	fflush(stdout);
	free(buff_ch1);
	free(buff_ch2);
	rp_Release();
	
	return NULL;


}