Exemplo n.º 1
0
int main(int argc, const char **argv)
{
  // To avoid the static initialization fiasco,
  type_poolt bees(true);
  type_pool = bees;

  c2goto_parseopt parseopt(argc, argv);
  return parseopt.main();
}
Exemplo n.º 2
0
Arquivo: minmax.c Projeto: iauns/ook
int
main(int argc, char* const argv[])
{
  parseopt(argc, argv);

  if(!ookinit()) {
    fprintf(stderr, "Initialization failed.\n");
    exit(EXIT_FAILURE);
  }
  const uint64_t bricksize[3] = { 64, 64, 64 };
  struct io* chained = chain2(DebugIO, StdCIO);

  struct ookfile* fin = ookread(StdCIO, input, vol, bricksize, itype, 1);
  if(!fin) { perror("open"); exit(EXIT_FAILURE); }
  free(chained);

  size_t bsize[3];
  ookmaxbricksize(fin, bsize);

  const size_t components = 1; /* our program assumes this.. */

  const size_t bytes_brick =
    bytewidth(itype) * components * bsize[0]*bsize[1]*bsize[2];
  void* data = malloc(bytes_brick);

  typedef void (t_func_apply)(const void*, double[2], const size_t);
  t_func_apply* fqn;
  switch(itype) {
    case OOK_I8: fqn = mmi8; break;
    case OOK_U8: fqn = mmu8; break;
    case OOK_I16: fqn = mmi16; break;
    case OOK_U16: fqn = mmu16; break;
    default: assert(false); fqn = NULL; break; /* FIXME! */
  }

  printf("\n");
  minmax[0] = FLT_MAX;
  minmax[1] = -FLT_MAX;
  for(size_t brick=0; brick < ookbricks(fin); ++brick) {
    size_t bs[3];
    ookbricksize(fin, brick, bs);
    assert(bs[0] > 0 && bs[1] > 0 && bs[2] > 0);
    ookbrick(fin, brick, data);
    fqn(data, minmax, bs[0]*bs[1]*bs[2]);
    printf("\rProcessed brick %5zu / %5zu... [%lf--%lf]", brick,
           ookbricks(fin), minmax[0], minmax[1]);
  }
  printf("\n");
  printf("Data range: %lf--%lf\n", minmax[0], minmax[1]);

  free(data);
  free(input);
  if(ookclose(fin) != 0) {
    fprintf(stderr, "Error closing files..\n");
  }
}
Exemplo n.º 3
0
/**
 * Parsuje i zwraca argumenty wywołania,
 * w przypadku braku któregokolwiek zwraca wartości domyślne.
 *
 * @param argv Argumenty wywołania (bez nazwy programu!).
 * @param argc Ilość argumentów.
 * @return Ładna struktura z zapakowanymi wszystkimi potrzebnymi danymi.
 */
struct params parseargs(char **argv, const size_t argc)
{
	/* Domyślne wartości, zgodne z treścią zadania. */
	struct params result = { { 0 }, 1000, 30, 3 };
	/* Czy wczytany został adres do którego drogę chcemy wyliczać? */
	bool addr = false;

	for (uint i = 0; i < argc; i++) {
		int retv = 0;

		if (OPTARG(argv[i], "-h", "--help")) {
			printhelp();
			exit(1);
		} else if (argv[i][0] == '-' && i < argc - 1) {
			retv = parseopt(argv[i], argv[i + 1], &result);
			i++;
		} else {
			retv = handle(
				"parse ip adress",
				inet_pton(AF_INET, argv[i], &result.addr.sin_addr)
			);

			addr = true;
		}

		/*
		 * `sscanf` zwraca ilość poprawnie zczytanych
		 * parametrów a `inet_pton` 1 jeżeli uda mu się
		 * sparsować adres. Wystarczy więc sprawdzić czy
		 * `retv` jest większy od zera, w przeciwnym razie
		 * argument jest nieprawidłowy.
		 */
		if (retv <= 0) {
			printf("Incorrect argument: %s.\n", argv[i]);
			printf("Try with `--help` for more information.\n");
			exit(1);
		}
	}

	if (!addr) {
		printf("Remote server address not given.\n");
		exit(1);
	}

	return result;
}
Exemplo n.º 4
0
Arquivo: conf.c Projeto: mhilton/conf
int
main(int argc, char **argv, char **envp)
{
	char const *error;
	ucl_object_t *obj;
	ucl_object_t const *kobj;
	struct ucl_parser *parser;
	int status = 0;

	parseopt(argc, argv);

	parser = ucl_parser_new(UCL_PARSER_NO_IMPLICIT_ARRAYS | UCL_PARSER_ZEROCOPY);
	if (parser == NULL) {
		err(EX_OSERR, "cannot create parser");
	}
	addvars(parser, envp);
	parse_file(parser);

	if ((error = ucl_parser_get_error(parser))) {
		errx(EX_DATAERR, "cannot load %s: %s", file, error);
	}

	obj = ucl_parser_get_object(parser);
	if (key != NULL && strcmp(key, ".") != 0)
		kobj = ucl_object_lookup_path(obj, key);
	else
		kobj = obj;
	if (env) {
		int nlen = 0;
		char *s;

		if (name != NULL)
			nlen = strlcpy(envkey, name, MAX_KEY_LEN);
		else if ((s = strrchr(key, '.')) != NULL)
			nlen = strlcpy(envkey, s + 1, MAX_KEY_LEN);
		if (kobj != NULL)
			expand(nlen, kobj);
		status = run(argv + cmdarg);
	} else if (kobj != NULL) {
		print(kobj);
	}

	ucl_object_unref(obj);
	ucl_parser_free(parser);
	exit(status);
}
Exemplo n.º 5
0
int main(int argc, char *argv[]) 
{
  int rc;
  FILE *initfd;
    
  rc = parseopt(argc, argv);
  if (rc < 0)
    return EXIT_FAILURE;
  else if (0 > rc)
    return EXIT_SUCCESS;
  
  if (1 == daemonize) {
    if (-1 == daemon(0, 0)) {
      perror("daemonize");
      rc =  EXIT_FAILURE;
      goto fail_daemon;
    }
  }
    
  /* Main Loop in log_packets */
  while (1) {
    sleep(period);
    
    initfd = fopen(MASON_INIT_PF, "w");
    if (!initfd)
      continue;

    fprintf(initfd, "%s", device);
    fclose(initfd);
  }
  
  rc = EXIT_SUCCESS;
  syslog(LOG_INFO, "daemon exiting\n");
 fail_daemon:
  return rc;
}
int main(int argc, char **argv)
{
    char *filename, *docFile, *codeDir, *srcSuffix, *flagFile, *consModule;
    char arg, *optarg, *buildFile, *apiFile, *xmlFile, *pyiFile;
    int optnr, exceptions, tracing, releaseGIL, parts, protHack, docs;
    int timestamp, was_flagFile;
    KwArgs kwArgs;
    FILE *file;
    sipSpec spec;
    stringList *versions, *backstops, *xfeatures, *extracts;

    /* Initialise. */
    sipVersion = SIP_VERSION_STR;
    includeDirList = NULL;
    versions = NULL;
    backstops = NULL;
    xfeatures = NULL;
    buildFile = NULL;
    codeDir = NULL;
    docFile = NULL;
    srcSuffix = NULL;
    flagFile = NULL;
    was_flagFile = FALSE;
    apiFile = NULL;
    xmlFile = NULL;
    pyiFile = NULL;
    consModule = NULL;
    extracts = NULL;
    exceptions = FALSE;
    tracing = FALSE;
    releaseGIL = FALSE;
    parts = 0;
    kwArgs = NoKwArgs;
    protHack = FALSE;
    docs = FALSE;
    timestamp = TRUE;

    /* Parse the command line. */
    optnr = 1;

    while ((arg = parseopt(argc, argv, "hVa:b:B:ec:d:fgI:j:km:op:Prs:t:Twx:X:y:z:", &flagFile, &optnr, &optarg)) != '\0')
        switch (arg)
        {
        case 'o':
            /* Generate docstrings. */
            docs = TRUE;
            break;

        case 'p':
            /* The name of the consolidated module. */
            consModule = optarg;
            break;

        case 'P':
            /* Enable the protected/public hack. */
            protHack = TRUE;
            break;

        case 'a':
            /* Where to generate the API file. */
            apiFile = optarg;
            break;

        case 'm':
            /* Where to generate the XML file. */
            xmlFile = optarg;
            break;

        case 'y':
            /* Where to generate the .pyi file. */
            pyiFile = optarg;
            break;

        case 'b':
            /* Generate a build file. */
            buildFile = optarg;
            break;

        case 'B':
            /* Define a backstop. */
            appendString(&backstops, optarg);
            break;

        case 'e':
            /* Enable exceptions. */
            exceptions = TRUE;
            break;

        case 'g':
            /* Always release the GIL. */
            releaseGIL = TRUE;
            break;

        case 'j':
            /* Generate the code in this number of parts. */
            parts = parseInt(optarg,'j');
            break;

        case 'z':
            /* Read a file for the next flags. */
            if (flagFile != NULL)
                fatal("The -z flag cannot be specified in an argument file\n");

            flagFile = optarg;
            was_flagFile = TRUE;
            break;

        case 'c':
            /* Where to generate the code. */
            codeDir = optarg;
            break;

        case 'd':
            /* Where to generate the documentation. */
            docFile = optarg;
            break;

        case 't':
            /* Which platform or version to generate code for. */
            appendString(&versions,optarg);
            break;

        case 'T':
            /*
             * Disable the timestamp in the header of generated files.  It is
             * now ignored apart from triggering a deprecation warning.
             */
            timestamp = FALSE;
            break;

        case 'x':
            /* Which features are disabled. */
            appendString(&xfeatures,optarg);
            break;

        case 'X':
            /* Which extracts are to be created. */
            appendString(&extracts, optarg);
            break;

        case 'I':
            /* Where to get included files from. */
            appendString(&includeDirList,optarg);
            break;

        case 'r':
            /* Enable tracing. */
            tracing = TRUE;
            break;

        case 's':
            /* The suffix to use for source files. */
            srcSuffix = optarg;
            break;

        case 'w':
            /* Enable warning messages. */
            warnings = TRUE;
            break;

        case 'f':
            /* Warning messages are fatal. */
            warnings_are_fatal = TRUE;
            break;

        case 'k':
            /* Allow keyword arguments in functions and methods. */
            kwArgs = AllKwArgs;
            break;

        case 'h':
            /* Help message. */
            help();
            break;

        case 'V':
            /* Display the version number. */
            version();
            break;

        default:
            usage();
        }

    if (optnr < argc)
    {
        file = NULL;
        filename = argv[optnr++];

        if (optnr < argc)
            usage();
    }
    else
    {
        file = stdin;
        filename = "stdin";
    }

    /* Issue warnings after they (might) have been enabled. */
    if (docFile != NULL)
        warning(DeprecationWarning, "the -d flag is deprecated\n");

    if (kwArgs != NoKwArgs)
        warning(DeprecationWarning, "the -k flag is deprecated\n");

    if (!timestamp)
        warning(DeprecationWarning, "the -T flag is ignored and deprecated\n");

    if (was_flagFile)
        warning(DeprecationWarning, "the -z flag is deprecated\n");

    /* Parse the input file. */
    parse(&spec, file, filename, versions, backstops, xfeatures, kwArgs,
            protHack);

    /* Verify and transform the parse tree. */
    transform(&spec);

    /* Generate code. */
    generateCode(&spec, codeDir, buildFile, docFile, srcSuffix, exceptions,
            tracing, releaseGIL, parts, versions, xfeatures, consModule, docs,
            FALSE);

    /* Generate any extracts. */
    generateExtracts(&spec, extracts);

    /* Generate the API file. */
    if (apiFile != NULL)
        generateAPI(&spec, spec.module, apiFile);

    /* Generate the XML export. */
    if (xmlFile != NULL)
        generateXML(&spec, spec.module,  xmlFile);

    /* Generate the .pyi file. */
    if (pyiFile != NULL)
        generateTypeHints(&spec, spec.module,  pyiFile);

    /* All done. */
    return 0;
}
Exemplo n.º 7
0
int main(int argc, char **argv)
{
    char *filename, *docFile, *codeDir, *srcSuffix, *flagFile, *consModule;
    char arg, *optarg, *buildFile, *apiFile, *xmlFile;
    int optnr, exceptions, tracing, releaseGIL, parts;
    FILE *file;
    sipSpec spec;
    stringList *versions, *xfeatures;

    /* Initialise. */
    sipVersion = VERSION;
    includeDirList = NULL;
    versions = NULL;
    xfeatures = NULL;
    buildFile = NULL;
    codeDir = NULL;
    docFile = NULL;
    srcSuffix = NULL;
    flagFile = NULL;
    apiFile = NULL;
    xmlFile = NULL;
    consModule = NULL;
    exceptions = FALSE;
    tracing = FALSE;
    releaseGIL = FALSE;
    parts = 0;

    /* Parse the command line. */
    optnr = 1;

    while ((arg = parseopt(argc, argv, "hVa:b:ec:d:gI:j:m:p:rs:t:wx:z:", &flagFile, &optnr, &optarg)) != '\0')
        switch (arg)
        {
        case 'p':
            /* The name of the consolidated module. */
            consModule = optarg;
            break;

        case 'a':
            /* Where to generate the API file. */
            apiFile = optarg;
            break;

        case 'm':
            /* Where to generate the XML file. */
            xmlFile = optarg;
            break;

        case 'b':
            /* Generate a build file. */
            buildFile = optarg;
            break;

        case 'e':
            /* Enable exceptions. */
            exceptions = TRUE;
            break;

        case 'g':
            /* Always release the GIL. */
            releaseGIL = TRUE;
            break;

        case 'j':
            /* Generate the code in this number of parts. */
            parts = parseInt(optarg,'j');
            break;

        case 'z':
            /* Read a file for the next flags. */
            if (flagFile != NULL)
                fatal("The -z flag cannot be specified in an argument file\n");

            flagFile = optarg;
            break;

        case 'c':
            /* Where to generate the code. */
            codeDir = optarg;
            break;

        case 'd':
            /* Where to generate the documentation. */
            docFile = optarg;
            break;

        case 't':
            /* Which platform or version to generate code for. */
            appendString(&versions,optarg);
            break;

        case 'x':
            /* Which features are disabled. */
            appendString(&xfeatures,optarg);
            break;

        case 'I':
            /* Where to get included files from. */
            appendString(&includeDirList,optarg);
            break;

        case 'r':
            /* Enable tracing. */
            tracing = TRUE;
            break;

        case 's':
            /* The suffix to use for source files. */
            srcSuffix = optarg;
            break;

        case 'w':
            /* Enable warning messages. */
            warnings = TRUE;
            break;

        case 'h':
            /* Help message. */
            help();
            break;

        case 'V':
            /* Display the version number. */
            version();
            break;

        default:
            usage();
        }

    if (optnr < argc)
    {
        file = NULL;
        filename = argv[optnr++];

        if (optnr < argc)
            usage();
    }
    else
    {
        file = stdin;
        filename = "stdin";
    }

    /* Parse the input file. */
    parse(&spec, file, filename, versions, xfeatures);

    /* Verify and transform the parse tree. */
    transform(&spec);

    /* Generate code. */
    generateCode(&spec, codeDir, buildFile, docFile, srcSuffix, exceptions,
            tracing, releaseGIL, parts, xfeatures, consModule);

    /* Generate the API file. */
    if (apiFile != NULL)
        generateAPI(&spec, spec.module, apiFile);

    /* Generate the XML export. */
    if (xmlFile != NULL)
        generateXML(&spec, spec.module,  xmlFile);

    /* All done. */
    return 0;
}
Exemplo n.º 8
0
int
main(int argc, char *argv[])
{
    char *ptr;
    char option;
    struct stat st;
    char *conffile = NULL;
    const char *const myname = "rnews";

    ln_log_open(myname);
    if (!initvars(argv[0], 0))
	init_failed(myname);

    while ((option = getopt(argc, argv, GLOBALOPTS "")) != -1) {
	if (parseopt(myname, option, optarg, &conffile))
	    continue;
	switch(option) {
	    default:
		usage();
		exit(EXIT_FAILURE);
	}
    }

    if (readconfig(conffile) != 0) {
	ln_log(LNLOG_SERR, LNLOG_CTOP, "Reading configuration failed: %m.\n");
	exit(2);
    }
    if (conffile)
	free(conffile);

    if (filterfile && !readfilter(filterfile)) {
	ln_log(LNLOG_SERR, LNLOG_CTOP,
		"%s: Cannot read filterfile %s, aborting.",
		argv[0], filterfile);
	log_unlink(lockfile, 0);
	exit(EXIT_FAILURE);
    }

    if (!init_post())
	init_failed(myname);

    umask((mode_t) 077);

    if (attempt_lock(LOCKWAIT)) {
	exit(EXIT_FAILURE);
    }

    rereadactive();
    readlocalgroups();
    if (!argv[optind])
	fprocessfile(stdin);	/* process stdin */
    while ((ptr = argv[optind++])) {
	if (stat(ptr, &st) == 0) {
	    if (S_ISDIR(st.st_mode))
		processdir(ptr);
	    else if (S_ISREG(st.st_mode))
		processfile(ptr);
	    else
		ln_log(LNLOG_SERR, LNLOG_CTOP,
		       "%s: cannot open %s\n", argv[0], ptr);
	} else
	    ln_log(LNLOG_SERR, LNLOG_CTOP,
		   "%s: cannot stat %s\n", argv[0], ptr);
    }
    writeactive();		/* write groupinfo file */
    freeallfilter(filter);
    log_unlink(lockfile, 0);
    exit(0);
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
	char *rawfilename = NULL;
	int numiter = 250;
	int use_apc = 1;
	int use_normalization = 0;
	conjugrad_float_t lambda_single = F001; // 0.01
	conjugrad_float_t lambda_pair = FInf;
	conjugrad_float_t lambda_pair_factor = F02; // 0.2
	int conjugrad_k = 5;
	conjugrad_float_t conjugrad_eps = 0.01;

	parse_option *optList, *thisOpt;

	char *optstr;
	char *old_optstr = malloc(1);
	old_optstr[0] = 0;
	optstr = concat("r:i:n:w:k:e:l:ARh?", old_optstr);
	free(old_optstr);

#ifdef OPENMP
	int numthreads = 1;
	old_optstr = optstr;
	optstr = concat("t:", optstr);
	free(old_optstr);
#endif

#ifdef CUDA
	int use_def_gpu = 0;
	old_optstr = optstr;
	optstr = concat("d:", optstr);
	free(old_optstr);
#endif

#ifdef MSGPACK
	char* msgpackfilename = NULL;
	old_optstr = optstr;
	optstr = concat("b:", optstr);
	free(old_optstr);
#endif

	optList = parseopt(argc, argv, optstr);
	free(optstr);

	char* msafilename = NULL;
	char* matfilename = NULL;
	char* initfilename = NULL;

	conjugrad_float_t reweighting_threshold = F08; // 0.8

	while(optList != NULL) {
		thisOpt = optList;
		optList = optList->next;

		switch(thisOpt->option) {
#ifdef OPENMP
			case 't':
				numthreads = atoi(thisOpt->argument);

#ifdef CUDA
				use_def_gpu = -1; // automatically disable GPU if number of threads specified
#endif
				break;
#endif
#ifdef CUDA
			case 'd':
				use_def_gpu = atoi(thisOpt->argument);
				break;
#endif
#ifdef MSGPACK
			case 'b':
				msgpackfilename = thisOpt->argument;
				break;
#endif
			case 'r':
				rawfilename = thisOpt->argument;
				break;
			case 'i':
				initfilename = thisOpt->argument;
				break;
			case 'n':
				numiter = atoi(thisOpt->argument);
				break;
			case 'w':
				reweighting_threshold = (conjugrad_float_t)atof(thisOpt->argument);
				break;
			case 'l':
				lambda_pair_factor = (conjugrad_float_t)atof(thisOpt->argument);
				break;
			case 'k':
				conjugrad_k = (int)atoi(thisOpt->argument);
				break;
			case 'e':
				conjugrad_eps = (conjugrad_float_t)atof(thisOpt->argument);
				break;
			case 'A':
				use_apc = 0;
				break;
			case 'R':
				use_normalization = 1;
				break;
			case 'h':
			case '?':
				usage(argv[0], 1);
				break;

			case 0:
				if(msafilename == NULL) {
					msafilename = thisOpt->argument;
				} else if(matfilename == NULL) {
					matfilename = thisOpt->argument;
				} else {
					usage(argv[0], 0);
				}
				break;
			default:
				die("Unknown argument"); 
		}

		free(thisOpt);
	}

	if(msafilename == NULL || matfilename == NULL) {
		usage(argv[0], 0);
	}


	FILE *msafile = fopen(msafilename, "r");
	if( msafile == NULL) {
		printf("Cannot open %s!\n\n", msafilename);
		return 2;
	}

#ifdef JANSSON
	char* metafilename = malloc(2048);
	snprintf(metafilename, 2048, "%s.meta.json", msafilename);
	
	FILE *metafile = fopen(metafilename, "r");
	json_t *meta;
	if(metafile == NULL) {
		// Cannot find .meta.json file - create new empty metadata
		meta = meta_create();
	} else {
		// Load metadata from matfile.meta.json
		meta = meta_read_json(metafile);
		fclose(metafile);
	}

	json_object_set(meta, "method", json_string("ccmpred"));

	json_t *meta_step = meta_add_step(meta, "ccmpred");
	json_object_set(meta_step, "version", json_string(__VERSION));

	json_t *meta_parameters = json_object();
	json_object_set(meta_step, "parameters", meta_parameters);

	json_t *meta_steps = json_array();
	json_object_set(meta_step, "iterations", meta_steps);

	json_t *meta_results = json_object();
	json_object_set(meta_step, "results", meta_results);

#endif

	int ncol, nrow;
	unsigned char* msa = read_msa(msafile, &ncol, &nrow);
	fclose(msafile);

	int nsingle = ncol * (N_ALPHA - 1);
	int nvar = nsingle + ncol * ncol * N_ALPHA * N_ALPHA;
	int nsingle_padded = nsingle + N_ALPHA_PAD - (nsingle % N_ALPHA_PAD);
	int nvar_padded = nsingle_padded + ncol * ncol * N_ALPHA * N_ALPHA_PAD;

#ifdef CURSES
	bool color = detect_colors();
#else
	bool color = false;
#endif

	logo(color);

#ifdef CUDA
	int num_devices, dev_ret;
	struct cudaDeviceProp prop;
	dev_ret = cudaGetDeviceCount(&num_devices);
	if(dev_ret != CUDA_SUCCESS) {
		num_devices = 0;
	}


	if(num_devices == 0) {
		printf("No CUDA devices available, ");
		use_def_gpu = -1;
	} else if (use_def_gpu < -1 || use_def_gpu >= num_devices) {
		printf("Error: %d is not a valid device number. Please choose a number between 0 and %d\n", use_def_gpu, num_devices - 1);
		exit(1);
	} else {
		printf("Found %d CUDA devices, ", num_devices);
	}

	if (use_def_gpu != -1) {
		cudaError_t err = cudaSetDevice(use_def_gpu);
		if(cudaSuccess != err) {
			printf("Error setting device: %d\n", err);
			exit(1);
		}
		cudaGetDeviceProperties(&prop, use_def_gpu);
		printf("using device #%d: %s\n", use_def_gpu, prop.name);

		size_t mem_free, mem_total;
		err = cudaMemGetInfo(&mem_free, &mem_total);
		if(cudaSuccess != err) {
			printf("Error getting memory info: %d\n", err);
			exit(1);
		}

		size_t mem_needed = nrow * ncol * 2 + // MSAs
		                    sizeof(conjugrad_float_t) * nrow * ncol * 2 + // PC, PCS
		                    sizeof(conjugrad_float_t) * nrow * ncol * N_ALPHA_PAD + // PCN
		                    sizeof(conjugrad_float_t) * nrow + // Weights
		                    (sizeof(conjugrad_float_t) * ((N_ALPHA - 1) * ncol + ncol * ncol * N_ALPHA * N_ALPHA_PAD)) * 4;

		setlocale(LC_NUMERIC, "");
		printf("Total GPU RAM:  %'17lu\n", mem_total);
		printf("Free GPU RAM:   %'17lu\n", mem_free);
		printf("Needed GPU RAM: %'17lu ", mem_needed);

		if(mem_needed <= mem_free) {
			printf("✓\n");
		} else {
			printf("⚠\n");
		}

#ifdef JANSSON
		json_object_set(meta_parameters, "device", json_string("gpu"));
		json_t* meta_gpu = json_object();
		json_object_set(meta_parameters, "gpu_info", meta_gpu);

		json_object_set(meta_gpu, "name", json_string(prop.name));
		json_object_set(meta_gpu, "mem_total", json_integer(mem_total));
		json_object_set(meta_gpu, "mem_free", json_integer(mem_free));
		json_object_set(meta_gpu, "mem_needed", json_integer(mem_needed));
#endif


	} else {
		printf("using CPU");
#ifdef JANSSON
		json_object_set(meta_parameters, "device", json_string("cpu"));
#endif

#ifdef OPENMP
		printf(" (%d thread(s))", numthreads);
#ifdef JANSSON
		json_object_set(meta_parameters, "cpu_threads", json_integer(numthreads));
#endif
#endif
		printf("\n");

	}
#else // CUDA
	printf("using CPU");
#ifdef JANSSON
	json_object_set(meta_parameters, "device", json_string("cpu"));
#endif
#ifdef OPENMP
	printf(" (%d thread(s))\n", numthreads);
#ifdef JANSSON
	json_object_set(meta_parameters, "cpu_threads", json_integer(numthreads));
#endif
#endif // OPENMP
	printf("\n");
#endif // CUDA

	conjugrad_float_t *x = conjugrad_malloc(nvar_padded);
	if( x == NULL) {
		die("ERROR: Not enough memory to allocate variables!");
	}
	memset(x, 0, sizeof(conjugrad_float_t) * nvar_padded);

	// Auto-set lambda_pair
	if(isnan(lambda_pair)) {
		lambda_pair = lambda_pair_factor * (ncol - 1);
	}

	// fill up user data struct for passing to evaluate
	userdata *ud = (userdata *)malloc( sizeof(userdata) );
	if(ud == 0) { die("Cannot allocate memory for user data!"); }
	ud->msa = msa;
	ud->ncol = ncol;
	ud->nrow = nrow;
	ud->nsingle = nsingle;
	ud->nvar = nvar;
	ud->lambda_single = lambda_single;
	ud->lambda_pair = lambda_pair;
	ud->weights = conjugrad_malloc(nrow);
	ud->reweighting_threshold = reweighting_threshold;

	if(initfilename == NULL) {
		// Initialize emissions to pwm
		init_bias(x, ud);
	} else {
		// Load potentials from file
		read_raw(initfilename, ud, x);
	}

	// optimize with default parameters
	conjugrad_parameter_t *param = conjugrad_init();

	param->max_iterations = numiter;
	param->epsilon = conjugrad_eps;
	param->k = conjugrad_k;
	param->max_linesearch = 5;
	param->alpha_mul = F05;
	param->ftol = 1e-4;
	param->wolfe = F02;


	int (*init)(void *) = init_cpu;
	int (*destroy)(void *) = destroy_cpu;
	conjugrad_evaluate_t evaluate = evaluate_cpu;

#ifdef OPENMP
	omp_set_num_threads(numthreads);
	if(numthreads > 1) {
		init = init_cpu_omp;
		destroy = destroy_cpu_omp;
		evaluate = evaluate_cpu_omp;
	}
#endif

#ifdef CUDA
	if(use_def_gpu != -1) {
		init = init_cuda;
		destroy = destroy_cuda;
		evaluate = evaluate_cuda;
	}
#endif

	init(ud);

#ifdef JANSSON


	json_object_set(meta_parameters, "reweighting_threshold", json_real(ud->reweighting_threshold));
	json_object_set(meta_parameters, "apc", json_boolean(use_apc));
	json_object_set(meta_parameters, "normalization", json_boolean(use_normalization));

	json_t *meta_regularization = json_object();
	json_object_set(meta_parameters, "regularization", meta_regularization);

	json_object_set(meta_regularization, "type", json_string("l2")); 
	json_object_set(meta_regularization, "lambda_single", json_real(lambda_single));
	json_object_set(meta_regularization, "lambda_pair", json_real(lambda_pair));
	json_object_set(meta_regularization, "lambda_pair_factor", json_real(lambda_pair_factor));

	json_t *meta_opt = json_object();
	json_object_set(meta_parameters, "optimization", meta_opt);

	json_object_set(meta_opt, "method", json_string("libconjugrad"));
	json_object_set(meta_opt, "float_bits", json_integer((int)sizeof(conjugrad_float_t) * 8));
	json_object_set(meta_opt, "max_iterations", json_integer(param->max_iterations));
	json_object_set(meta_opt, "max_linesearch", json_integer(param->max_linesearch));
	json_object_set(meta_opt, "alpha_mul", json_real(param->alpha_mul));
	json_object_set(meta_opt, "ftol", json_real(param->ftol));
	json_object_set(meta_opt, "wolfe", json_real(param->wolfe));


	json_t *meta_msafile = meta_file_from_path(msafilename);
	json_object_set(meta_parameters, "msafile", meta_msafile);
	json_object_set(meta_msafile, "ncol", json_integer(ncol));
	json_object_set(meta_msafile, "nrow", json_integer(nrow));

	if(initfilename != NULL) {
		json_t *meta_initfile = meta_file_from_path(initfilename);
		json_object_set(meta_parameters, "initfile", meta_initfile);
		json_object_set(meta_initfile, "ncol", json_integer(ncol));
		json_object_set(meta_initfile, "nrow", json_integer(nrow));
	}

	double neff = 0;
	for(int i = 0; i < nrow; i++) {
		neff += ud->weights[i];
	}

	json_object_set(meta_msafile, "neff", json_real(neff));

	ud->meta_steps = meta_steps;

#endif

	printf("\nWill optimize %d %ld-bit variables\n\n", nvar, sizeof(conjugrad_float_t) * 8);

	if(color) { printf("\x1b[1m"); }
	printf("iter\teval\tf(x)    \t║x║     \t║g║     \tstep\n");
	if(color) { printf("\x1b[0m"); }


	conjugrad_float_t fx;
	int ret;
#ifdef CUDA
	if(use_def_gpu != -1) {
		conjugrad_float_t *d_x;
		cudaError_t err = cudaMalloc((void **) &d_x, sizeof(conjugrad_float_t) * nvar_padded);
		if (cudaSuccess != err) {
			printf("CUDA error No. %d while allocation memory for d_x\n", err);
			exit(1);
		}
		err = cudaMemcpy(d_x, x, sizeof(conjugrad_float_t) * nvar_padded, cudaMemcpyHostToDevice);
		if (cudaSuccess != err) {
			printf("CUDA error No. %d while copying parameters to GPU\n", err);
			exit(1);
		}
		ret = conjugrad_gpu(nvar_padded, d_x, &fx, evaluate, progress, ud, param);
		err = cudaMemcpy(x, d_x, sizeof(conjugrad_float_t) * nvar_padded, cudaMemcpyDeviceToHost);
		if (cudaSuccess != err) {
			printf("CUDA error No. %d while copying parameters back to CPU\n", err);
			exit(1);
		}
		err = cudaFree(d_x);
		if (cudaSuccess != err) {
			printf("CUDA error No. %d while freeing memory for d_x\n", err);
			exit(1);
		}
	} else {
	ret = conjugrad(nvar_padded, x, &fx, evaluate, progress, ud, param);
	}
#else
	ret = conjugrad(nvar_padded, x, &fx, evaluate, progress, ud, param);
#endif

	printf("\n");
	printf("%s with status code %d - ", (ret < 0 ? "Exit" : "Done"), ret);

	if(ret == CONJUGRAD_SUCCESS) {
		printf("Success!\n");
	} else if(ret == CONJUGRAD_ALREADY_MINIMIZED) {
		printf("Already minimized!\n");
	} else if(ret == CONJUGRADERR_MAXIMUMITERATION) {
		printf("Maximum number of iterations reached.\n");
	} else {
		printf("Unknown status code!\n");
	}

	printf("\nFinal fx = %f\n\n", fx);

	FILE* out = fopen(matfilename, "w");
	if(out == NULL) {
		printf("Cannot open %s for writing!\n\n", matfilename);
		return 3;
	}

	conjugrad_float_t *outmat = conjugrad_malloc(ncol * ncol);

	FILE *rawfile = NULL;
	if(rawfilename != NULL) {
		printf("Writing raw output to %s\n", rawfilename);
		rawfile = fopen(rawfilename, "w");

		if(rawfile == NULL) {
			printf("Cannot open %s for writing!\n\n", rawfilename);
			return 4;
		}

		write_raw(rawfile, x, ncol);
	}

#ifdef MSGPACK

	FILE *msgpackfile = NULL;
	if(msgpackfilename != NULL) {
		printf("Writing msgpack raw output to %s\n", msgpackfilename);
		msgpackfile = fopen(msgpackfilename, "w");

		if(msgpackfile == NULL) {
			printf("Cannot open %s for writing!\n\n", msgpackfilename);
			return 4;
		}

#ifndef JANSSON
		void *meta = NULL;
#endif

	}
#endif

	sum_submatrices(x, outmat, ncol);

	if(use_apc) {
		apc(outmat, ncol);
	}

	if(use_normalization) {
		normalize(outmat, ncol);
	}

	write_matrix(out, outmat, ncol, ncol);

#ifdef JANSSON

	json_object_set(meta_results, "fx_final", json_real(fx));
	json_object_set(meta_results, "num_iterations", json_integer(json_array_size(meta_steps)));
	json_object_set(meta_results, "opt_code", json_integer(ret));

	json_t *meta_matfile = meta_file_from_path(matfilename);
	json_object_set(meta_results, "matfile", meta_matfile);

	if(rawfilename != NULL) {
		json_object_set(meta_results, "rawfile", meta_file_from_path(rawfilename));
	}

	if(msgpackfilename != NULL) {
		json_object_set(meta_results, "msgpackfile", meta_file_from_path(msgpackfilename));
	}

	fprintf(out, "#>META> %s", json_dumps(meta, JSON_COMPACT));
	if(rawfile != NULL) {
		fprintf(rawfile, "#>META> %s", json_dumps(meta, JSON_COMPACT));
	}
#endif


	if(rawfile != NULL) {
		fclose(rawfile);
	}

#ifdef MSGPACK
	if(msgpackfile != NULL) {
		write_raw_msgpack(msgpackfile, x, ncol, meta);
		fclose(msgpackfile);
	}

#endif

	fflush(out);
	fclose(out);

	destroy(ud);

	conjugrad_free(outmat);
	conjugrad_free(x);
	conjugrad_free(ud->weights);
	free(ud);
	free(msa);
	free(param);
	
	printf("Output can be found in %s\n", matfilename);

	return 0;
}
Exemplo n.º 10
0
Arquivo: cast8.c Projeto: iauns/ook
int
main(int argc, char* const argv[])
{
  parseopt(argc, argv);

  if(!ookinit()) {
    fprintf(stderr, "Initialization failed.\n");
    exit(EXIT_FAILURE);
  }
  const uint64_t bricksize[3] = { vol[0], 16, 16 };

  struct ookfile* fin = ookread(StdCIO, input, vol, bricksize, itype, 1);
  if(!fin) { perror("ookread"); exit(EXIT_FAILURE); }
  free(input); input = NULL;
  struct ookfile* fout = ookcreate(StdCIO, output, vol, bricksize, OOK_U8, 1);
  if(!fout) {
    perror("ookcreate");
    ookclose(fin);
    exit(EXIT_FAILURE);
  }
  free(output); output = NULL;

  size_t bsize[3];
  ookmaxbricksize(fin, bsize);

  const size_t components = 1; /* our program assumes this.. */

  const size_t bytes_brick =
    bytewidth(itype) * components * bsize[0]*bsize[1]*bsize[2];
  void* data = malloc(bytes_brick);
  void* odata = malloc(sizeof(uint8_t)*components * bsize[0]*bsize[1]*bsize[2]);

  typedef void (t_func_apply)(const void*, void*, const size_t);
  t_func_apply* fqn;
  switch(itype) {
    case OOK_I8: fqn = fromi8; break;
    case OOK_U8:
      fprintf(stderr, "u8 to u8 makes no sense.\n");
      exit(EXIT_FAILURE);
      break;
    case OOK_I16: fqn = fromi16; break;
    case OOK_U16: fqn = fromu16; break;
    default: assert(false); fqn = NULL; break; /* FIXME! */
  }

  printf("\n");
  for(size_t brick=0; brick < ookbricks(fin); ++brick) {
    size_t bs[3];
    ookbricksize(fin, brick, bs);
    assert(bs[0] > 0 && bs[1] > 0 && bs[2] > 0);

    ookbrick(fin, brick, data);
    fqn(data, odata, bs[0]*bs[1]*bs[2]);
    ookwrite(fout, brick, odata);
    printf("\rProcessed brick %5zu / %5zu...", brick, ookbricks(fin));
  }
  printf("\n");

  free(data);
  free(odata);
  if(ookclose(fin) != 0) {
    fprintf(stderr, "Error closing input\n");
  }
  if(ookclose(fout) != 0) {
    fprintf(stderr, "Error closing output!\n");
  }
}
Exemplo n.º 11
0
int main(int argc, char ** argv)
{
    t_program_opts options;
    Construct_t_program_opts(&options);
    
    parseopt(argc, argv, &options);
    g_debugLevel = options.debugLevel;
    DebugOutput(1, "Debug level: %d\n", g_debugLevel);
    if (options.showHelp)
    {
        DebugOutput(2, "Show help text option selected.\n");
        ShowHelp();
    }
    if (options.showVersion)
    {
        printf("Version: %s\n", GIT_VERSION);
    }
    // Things we need a file for
    if (options.extractFiles || options.showContentsLong || options.showContentsShort || options.addFiles || options.deleteFiles)
    {
        if (options.archiveFile)
        {
            int fd;
            // Readonly operations
            if (options.extractFiles || options.showContentsLong || options.showContentsShort)
            {
                fd = open(options.archiveFile, O_RDONLY);
                CheckOpen(fd);
                CheckHeader(fd);
                
                if (options.showContentsShort)
                {
                    ListOtarShort(fd, &options);
                    close(fd);
                }
                if (options.showContentsLong)
                {
                    
                }
                if (options.extractFiles)
                {
                    ExtractFile(fd, &options);
                    umask(0);
                }
            }
            else if (options.addFiles)
            {
                umask(0);
                fd = open(options.archiveFile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
                CheckOpen(fd);
                AddFile(fd, &options);
            }
            else if (options.deleteFiles)
            {
                fd = open(options.archiveFile, O_RDWR);
                CheckOpen(fd);
                CheckHeader(fd);
                RemoveFile(fd, &options);
            }
        }
        else
        {
            fprintf(stderr, "No archive file specified, but you requested an operation that requires one.\n");
            ShowHelp();
        }
    }
    Cleanup_t_program_opts(&options);
    return 0;
}
Exemplo n.º 12
0
int
main(int argc, char **argv)
{
    int return_code = 0;
    int fd = (-1);              /* fd == -1 means connection to fcron is not currently open */
    struct passwd *pass = NULL;

    rootuid = get_user_uid_safe(ROOTNAME);
    rootgid = get_group_gid_safe(ROOTGROUP);

    if (strrchr(argv[0], '/') == NULL)
        prog_name = argv[0];
    else
        prog_name = strrchr(argv[0], '/') + 1;

    user_uid = getuid();
    user_gid = getgid();
    if ((pass = getpwuid(user_uid)) == NULL)
        die("user \"%s\" is not in passwd file. Aborting.", USERNAME);
    user_str = strdup2(pass->pw_name);

    /* drop suid rights that we don't need, but keep the sgid rights
     * for now as we will need them for read_conf() and is_allowed() */
#ifdef USE_SETE_ID
    seteuid_safe(user_uid);
#endif
    if (setuid(user_uid) < 0)
        die_e("could not setuid() to %d", user_uid);

    /* interpret command line options */
    parseopt(argc, argv);

    /* read fcron.conf and update global parameters */
    read_conf();

    if (!is_allowed(user_str)) {
        die("User \"%s\" is not allowed to use %s. Aborting.", user_str,
            prog_name);
    }

    /* we don't need anymore special rights : drop remaining ones */
#ifdef USE_SETE_ID
    setegid_safe(user_gid);
#endif
    if (setgid(user_gid) < 0)
        die_e("could not setgid() to %d", user_gid);

    /* check for broken pipes ... */
    signal(SIGPIPE, sigpipe_handler);

    if (cmd_str == NULL)
        return_code = interactive_mode(fd);
    else
        return_code = talk_fcron(cmd_str, fd);

    xexit((return_code == OK) ? EXIT_OK : EXIT_ERR);

    /* never reached */
    return EXIT_OK;

}
Exemplo n.º 13
0
int
main(int argc, char **argv)
{

#ifdef HAVE_LIBPAM
    int    retcode = 0;
    const char * const * env;
#endif
#ifdef USE_SETE_ID
    struct passwd *pass;
#endif

    memset(buf, 0, sizeof(buf));
    memset(file, 0, sizeof(file));

    if (strrchr(argv[0],'/')==NULL) prog_name = argv[0];
    else prog_name = strrchr(argv[0],'/')+1;
    
    uid = getuid();

    /* get current dir */
    if ( getcwd(orig_dir, sizeof(orig_dir)) == NULL )
	die_e("getcwd");

    /* interpret command line options */
    parseopt(argc, argv);

#ifdef USE_SETE_ID
    if ( ! (pass = getpwnam(USERNAME)) )
	die("user \"%s\" is not in passwd file. Aborting.", USERNAME);
    fcrontab_uid = pass->pw_uid;
    fcrontab_gid = pass->pw_gid;

#ifdef HAVE_LIBPAM
    /* Open PAM session for the user and obtain any security
       credentials we might need */

    debug("username: %s", user);
    retcode = pam_start("fcrontab", user, &apamconv, &pamh);
    if (retcode != PAM_SUCCESS) die_pame(pamh, retcode, "Could not start PAM");
    retcode = pam_authenticate(pamh, 0);    /* is user really user? */
    if (retcode != PAM_SUCCESS)
	die_pame(pamh, retcode, "Could not authenticate user using PAM (%d)", retcode);
    retcode = pam_acct_mgmt(pamh, 0); /* permitted access? */
    if (retcode != PAM_SUCCESS)
	die_pame(pamh, retcode, "Could not init PAM account management (%d)", retcode);
    retcode = pam_setcred(pamh, PAM_ESTABLISH_CRED);
    if (retcode != PAM_SUCCESS) die_pame(pamh, retcode, "Could not set PAM credentials");
    retcode = pam_open_session(pamh, 0);
    if (retcode != PAM_SUCCESS) die_pame(pamh, retcode, "Could not open PAM session");

    env = (const char * const *) pam_getenvlist(pamh);
    while (env && *env) {
	if (putenv((char*) *env)) die_e("Could not copy PAM environment");
	env++;
    }

    /* Close the log here, because PAM calls openlog(3) and
       our log messages could go to the wrong facility */
    xcloselog();
#endif /* USE_PAM */

    if (uid != fcrontab_uid)
	if (seteuid(fcrontab_uid) != 0) 
	    die_e("Couldn't change euid to fcrontab_uid[%d]",fcrontab_uid);
    /* change directory */
    if (chdir(fcrontabs) != 0) {
	error_e("Could not chdir to %s", fcrontabs);
	xexit (EXIT_ERR);
    }
    /* get user's permissions */
    if (seteuid(uid) != 0) 
	die_e("Could not change euid to %d", uid); 
    if (setegid(fcrontab_gid) != 0) 
	die_e("Could not change egid to " GROUPNAME "[%d]", fcrontab_gid); 

#else /* USE_SETE_ID */

    if (setuid(ROOTUID) != 0 ) 
	die_e("Could not change uid to ROOTUID"); 
    if (setgid(ROOTGID) != 0)
    	die_e("Could not change gid to ROOTGID");
    /* change directory */
    if (chdir(fcrontabs) != 0) {
	error_e("Could not chdir to %s", fcrontabs);
	xexit (EXIT_ERR);
    }
#endif /* USE_SETE_ID */
    
    /* this program is seteuid : we set default permission mode
     * to 640 for a normal user, 600 for root, for security reasons */
    if ( asuid == ROOTUID )
	umask(066);  /* octal : '0' + number in octal notation */
    else
	umask(026);

    snprintf(buf, sizeof(buf), "%s.orig", user);

    /* determine what action should be taken */
    if ( file_opt ) {

	if ( strcmp(argv[file_opt], "-") == 0 )

	    xexit(install_stdin());

	else {

	    if ( *argv[file_opt] != '/' )
		/* this is just the file name, not the path : complete it */
		snprintf(file, sizeof(file), "%s/%s", orig_dir, argv[file_opt]);
	    else {
		strncpy(file, argv[file_opt], sizeof(file) - 1);
		file[sizeof(file)-1] = '\0';
	    }

	    if (make_file(file) == OK)
		xexit(EXIT_OK);
	    else
		xexit(EXIT_ERR);

	}

    } 

    /* remove user's entries */
    if ( rm_opt == 1 ) {
	if ( remove_fcrontab(1) == ENOENT )
	    fprintf(stderr, "no fcrontab for %s\n", user);
	xexit (EXIT_OK);
    }

    /* list user's entries */
    if ( list_opt == 1 ) {
	list_file(buf);
	xexit(EXIT_OK);
    }


    /* edit user's entries */
    if ( edit_opt == 1 ) {
	edit_file(buf);
	xexit(EXIT_OK);
    }

    /* reinstall user's entries */
    if ( reinstall_opt == 1 ) {
	reinstall(buf);
	xexit(EXIT_OK);
    }

    /* never reached */
    return EXIT_OK;
}
Exemplo n.º 14
0
int
main(int argc, char **argv)
{
    char *codeset = NULL;

    rootuid = get_user_uid_safe(ROOTNAME);
    rootgid = get_group_gid_safe(ROOTGROUP);

    /* we set it to 022 in order to get a pidfile readable by fcrontab
     * (will be set to 066 later) */
    saved_umask = umask(022);

    /* parse options */

    if (strrchr(argv[0], '/') == NULL)
        prog_name = argv[0];
    else
        prog_name = strrchr(argv[0], '/') + 1;

    {
        uid_t daemon_uid;
        if ((daemon_uid = getuid()) != rootuid)
            die("Fcron must be executed as root");
    }

    /* we have to set daemon_pid before the fork because it's
     * used in die() and die_e() functions */
    daemon_pid = getpid();

    /* save the value of the TZ env variable (used for option timezone) */
    orig_tz_envvar = strdup2(getenv("TZ"));

    parseopt(argc, argv);

    /* read fcron.conf and update global parameters */
    read_conf();

    /* initialize the logs before we become a daemon */
    xopenlog();

    /* change directory */

    if (chdir(fcrontabs) != 0)
        die_e("Could not change dir to %s", fcrontabs);

    /* Get the default locale character set for the mail
     * "Content-Type: ...; charset=" header */
    setlocale(LC_ALL, "");      /* set locale to system defaults or to
                                 * that specified by any  LC_* env vars */
    /* Except that "US-ASCII" is preferred to "ANSI_x3.4-1968" in MIME,
     * even though "ANSI_x3.4-1968" is the official charset name. */
    if ((codeset = nl_langinfo(CODESET)) != 0L &&
        strcmp(codeset, "ANSI_x3.4-1968") != 0)
        strncpy(default_mail_charset, codeset, sizeof(default_mail_charset));
    else
        strcpy(default_mail_charset, "US-ASCII");

    if (freopen("/dev/null", "r", stdin) == NULL)
        error_e("Could not open /dev/null as stdin");

    if (foreground == 0) {

        /* close stdout and stderr.
         * close unused descriptors
         * optional detach from controlling terminal */

        int fd;
        pid_t pid;

        switch (pid = fork()) {
        case -1:
            die_e("fork");
            break;
        case 0:
            /* child */
            break;
        default:
            /* parent */
/*  	    printf("%s[%d] " VERSION_QUOTED " : started.\n", */
/*  		   prog_name, pid); */
            exit(0);
        }

        daemon_pid = getpid();

        if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
#ifndef _HPUX_SOURCE
            ioctl(fd, TIOCNOTTY, 0);
#endif
            xclose_check(&fd, "/dev/tty");
        }

        if (freopen("/dev/null", "w", stdout) == NULL)
            error_e("Could not open /dev/null as stdout");
        if (freopen("/dev/null", "w", stderr) == NULL)
            error_e("Could not open /dev/null as stderr");

        /* close most other open fds */
        xcloselog();
        for (fd = 3; fd < 250; fd++)
            /* don't use xclose_check() as we do expect most of them to fail */
            (void)close(fd);

        /* finally, create a new session */
        if (setsid() == -1)
            error("Could not setsid()");

    }

    /* check if another fcron daemon is running, create pid file and lock it */
    get_lock();

    /* this program belongs to root : we set default permission mode
     * to  600 for security reasons, but we reset them to the saved
     * umask just before we run a job */
    umask(066);

    explain("%s[%d] " VERSION_QUOTED " started", prog_name, daemon_pid);

#ifdef HAVE_SIGNAL
    signal(SIGTERM, sigterm_handler);
    signal(SIGHUP, sighup_handler);
    siginterrupt(SIGHUP, 0);
    signal(SIGCHLD, sigchild_handler);
    siginterrupt(SIGCHLD, 0);
    signal(SIGUSR1, sigusr1_handler);
    siginterrupt(SIGUSR1, 0);
    signal(SIGUSR2, sigusr2_handler);
    siginterrupt(SIGUSR2, 0);
    /* we don't want SIGPIPE to kill fcron, and don't need to handle it */
    signal(SIGPIPE, SIG_IGN);
#elif HAVE_SIGSET
    sigset(SIGTERM, sigterm_handler);
    sigset(SIGHUP, sighup_handler);
    sigset(SIGCHLD, sigchild_handler);
    sigset(SIGUSR1, sigusr1_handler);
    sigset(SIGUSR2, sigusr2_handler);
    sigset(SIGPIPE, SIG_IGN);
#endif

    /* initialize job database */
    next_id = 0;

    /* initialize exe_array */
    exe_list = exe_list_init();

    /* initialize serial_array */
    serial_running = 0;
    serial_array_index = 0;
    serial_num = 0;
    serial_array_size = SERIAL_INITIAL_SIZE;
    serial_array =
        alloc_safe(serial_array_size * sizeof(cl_t *), "serial_array");

    /* initialize lavg_array */
    lavg_list = lavg_list_init();
    lavg_list->max_entries = lavg_queue_max;
    lavg_serial_running = 0;

#ifdef FCRONDYN
    /* initialize socket */
    init_socket();
#endif

    /* initialize random number generator :
     * WARNING : easy to guess !!! */
    /* we use the hostname and tv_usec in order to get different seeds
     * on two different machines starting fcron at the same moment */
    {
        char hostname[50];
        int i;
        unsigned int seed;
#ifdef HAVE_GETTIMEOFDAY
        struct timeval tv;      /* we use usec field to get more precision */
        gettimeofday(&tv, NULL);
        seed = ((unsigned int)tv.tv_usec) ^ ((unsigned int)tv.tv_sec);
#else
        seed = (unsigned int)time(NULL);
#endif
        gethostname(hostname, sizeof(hostname));

        for (i = 0; i < sizeof(hostname) - sizeof(seed); i += sizeof(seed))
            seed ^= (unsigned int)*(hostname + i);

        srand(seed);
    }

    main_loop();

    /* never reached */
    return EXIT_OK;
}
Exemplo n.º 15
0
Arquivo: ex1.c Projeto: pierrix/DLFree
int
main(int argc, char** argv){
  gxp_man_t gxp;
  dlfree_comm_node_t comm_node;
  char filename[100];

  int iter, rttype, seed;
  float topology_param, size;

  parseopt(argc, argv, filename, &topology_param, &size, &rttype, &iter, &seed);

  gxp = gxp_man_create();
  comm_node = dlfree_comm_node_create(gxp_man_peer_id(gxp));
  gxp_man_init(gxp);

  if (1) {
    /* if necessary, set address priority: */
    /* below we give priority to 10.**, then 192.**, 
       then any iface (excluding 10.**, 127.**) */
    const char *prio[] = {"10.5"};
    gxp_man_set_iface_prio(gxp, prio, sizeof(prio) / sizeof(prio[0]));
  }

  /* first choose connection scheme */

#if 0
   gxp_man_connect_all(gxp, comm_node); 
#elif 0
   gxp_man_connect_random(gxp, comm_node, topology_param, seed); 
#elif 1
   gxp_man_connect_ring(gxp, comm_node);
#elif 0
   gxp_man_connect_line(gxp, comm_node);
#elif 0
   gxp_man_connect_with_gateway(gxp, comm_node, 5, (int)topology_param, density, seed);
#elif 0
  gxp_man_connect_locality_aware(gxp, comm_node, filename, (int)topology_param, seed);
#else
#error specify connection scheme
#endif

  /* compute dlfree routing table */
  
  gxp_man_compute_rt(gxp, comm_node, filename, rttype, seed);
  
  gxp_man_sync(gxp);

  /* do some communication */

#if 1
  send_all2all(gxp, comm_node, 1024 * 1024 * size, iter);
#elif 0
  send_all2one(gxp, comm_node, /* dst_idx = */ 0, 1024 * 1024 * size, iter);
#elif 0
  send_one2all(gxp, comm_node, /* src_idx = */ 0, 1024 * 1024 * size, iter);
#else
#error choose a communication pattern
#endif

  gxp_man_sync(gxp);
  
  dlfree_comm_node_destroy(comm_node);
  
  gxp_man_destroy(gxp);
  return 0;
}