Ejemplo n.º 1
0
/* markov main: markov-chain random text generation */
int main(void)
{
	int i, nwords = MAXGEN;
	char *prefix[NPREF];		/* current input prefix */

	int c;
	long seed;

	setProgName("markov");
	seed = time(NULL);

	srand(seed);
	for (i = 0; i < NPREF; i++)	/* set up initial prefix */
		prefix[i] = NONWORD;
	build(prefix, stdin);
	add(prefix, NONWORD);
	generate(nwords);
	return 0;
}   
Ejemplo n.º 2
0
int main(int argc, char **argv) {
	setProgName(argv[0]);
	checkArgs(argc, 1, "port number");

	char socketBuffer[1024];
	int usbfd = initSerial(115200, "/dev/ttyUSB0" );
	int port = atoi(argv[1]);
	int serverfd =  initServer(port);

	while(1) {
		// Listen for incoming calls
		int clientfd = eaccept(serverfd);
		int ret = myRead( clientfd, socketBuffer, 1024 );
		while( ret > 0 ) {
			handleRequest(socketBuffer, &clientfd, &usbfd);
			ret = myRead(clientfd, socketBuffer, 1024);
		}
		close(clientfd);
	}

	return EXIT_SUCCESS;
}
Ejemplo n.º 3
0
// Main program entry point
int main(int argc, char **argv) {
    for (int i = 0; i < (1 + MAX_PLAYERS); i++)
        threadsFree[i] = -1;

    setProgName(argv[0]);
    debugDisable();
    infoPrint("Server Gruppe 01");
    userInit();

    // Create PID lock file or exit if it already exists
    debugPrint("Making sure we're running only once...");
    if (singleton(LOCKFILE) != 0)
        return 1;

    // Socket structure that could be modified by the command line arguments
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(PORT); // Use the default port defined in "common"!

    // Prepare parsing the command line options using getopt()
    debugPrint("Parsing command line options...");
    const char* short_options = "hvp:";
    struct option long_options[] = {
        { "help", no_argument, 0, 'h' },
        { "verbose", no_argument, 0, 'v' },
        { "port", required_argument, 0, 'p' },
        { NULL, 0, NULL, 0 }
    };

    // Actual getopt() loop
    int option_index = 0;
    int loop = 1;
    while (loop != 0) {
        int c = getopt_long(argc, argv, short_options, long_options, &option_index);
        switch (c) {
            // Show help text when using -h
            case 'h':
                show_help();
                exit(1);
                break;

            // Enable verbose (debug) output
            case 'v':
                debugEnable();
                break;

            // Set port to listen on
            case 'p':
                if(optarg) {
                    if (isOnlyDigits(optarg)) {
                        server.sin_port = htons(atoi(optarg));
                    } else {
                        errorPrint("Port has to be a decimal number!");
                        exit(1);
                    }
                }
                break;

            // Unknown option, show error & help message
            default:
            case '?':
                errorPrint("Option not implemented yet -- %s (%c)", argv[optind-1], c);
                show_help();
                exit(1);
                break;

            // All options have been parsed
            case -1:
                loop = 0;
                break;
        }
    }

    infoPrint("Serverport: %i", ntohs(server.sin_port));

    // Create the pipes that will be used to communicate with the loader
    debugPrint("Creating Pipes...");
    if (!createPipes())
        return 1;

    // Actually fork and run the loader as child process
    debugPrint("Forking to run loader...");
    if (!forkLoader())
        return 1;

    debugPrint("Starting Threads...");

    // Start the score agent thread
    if (pthread_create(&threads[0], NULL, scoreThread, NULL) != 0) {
        threadsFree[0] = -2;
        errnoPrint("pthread_create");
        return 1;
    }

    clientInit();

    // Create the listening socket
    debugPrint("Creating socket...");
    int listen_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_socket == -1) {
        errnoPrint("socket");
        return 1;
    }

    // Enable address reusing, so we don't get bind errors
    int on = 1;
    setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    // Register our Interrupt Signal handler
    signal(SIGINT, intHandler);

    // Store the listening socket in our user database
    userSetMainSocket(listen_socket);

    // Actually bind the listening socket
    if (bind(listen_socket, (struct sockaddr*) &server, sizeof(struct sockaddr_in)) == -1) {
        errnoPrint("bind");
        close(listen_socket);
        closePipes();
        loaderCloseSharedMemory();
        return 1;
    }

    // Prepare the pselect() timeout data structure
    fd_set fds;
    struct timespec ts;
    ts.tv_sec = 0;
    ts.tv_nsec = SOCKET_TIMEOUT * 1000000;
    sigset_t blockset;
    sigfillset(&blockset);
    sigdelset(&blockset, SIGINT);

    // Main thread main loop, waiting for new connections
    debugPrint("Waiting for connections...");
    while (getRunning()) {
        // Listen to the listening socket
        if (listen(listen_socket, MAX_QUERYS) == -1) {
            errnoPrint("listen");
            close(listen_socket);
            closePipes();
            loaderCloseSharedMemory();
            cleanCategories();
            return 1;
        }

        // Wait for activity on the listening socket
        FD_ZERO(&fds);
        FD_SET(listen_socket, &fds);
        int retval = pselect(listen_socket + 1, &fds, NULL, NULL, &ts, &blockset);
        if (retval == -1) {
            if (errno == EINTR) {
                // We should exit because the user pressed Ctrl + C
                close(listen_socket);
                closePipes();
                loaderCloseSharedMemory();
                cleanCategories();
                return 0;
            } else {
                // pselect encountered an error!
                errnoPrint("select");
                close(listen_socket);
                closePipes();
                loaderCloseSharedMemory();
                cleanCategories();
                return 1;
            }
        } else if (retval == 0) {
            // Nothing happened and pselect timed out
            continue;
        } else {
            // We have a new connection, accept it
            struct sockaddr_in remote_host;
            socklen_t sin_size = sizeof(struct sockaddr_in);
            int client_socket = accept(listen_socket, (struct sockaddr *) &remote_host, &sin_size);
            if (client_socket == -1) {
                errnoPrint("accept");
                close(listen_socket);
                closePipes();
                loaderCloseSharedMemory();
                cleanCategories();
                return 1;
            }

            debugPrint("Got a new connection! Performing Login...");
            loginHandleSocket(client_socket);
        }
    }

    // Clean up behind ourselves
    close(listen_socket);
    closePipes();
    loaderCloseSharedMemory();
    cleanCategories();

    pthread_exit(NULL);
    return 0;
}
Ejemplo n.º 4
0
int main(int argc, char ** argv)
{
	char *server, *service;
	struct addrinfo *addr_info, *p, hints;
	int ret, i;
	int sockets[128];
	int numsockets = 0;

	setProgName(argv[0]);	/* For our infoPrint/errorPrint functions */

	if (argc <= 1)
	{
		errorPrint("Simple Echo-Server");
		errorPrint("Usage: %s [BINDADDR] [SERVICE]", argv[0]);
		errorPrint("Example: %s localhost 8080", argv[0]);
		exit(1);
	}
	if (argc == 3) {
		server = argv[1];
		service = argv[2];
	} else {
		server = NULL;
		service = argv[1];
	}

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE | AI_V4MAPPED;

	/* RTFM: getaddrinfo */
	ret = getaddrinfo(server, service, &hints, &addr_info);
	if (ret)
	{
		errorPrint("Error in getaddrinfo: %s", gai_strerror(ret));
		exit(1);
	}

	p = addr_info;
	while (p)
	{
		int s;
		char dst[INET6_ADDRSTRLEN];
		char service[INET6_ADDRSTRLEN];
		int on = 1;

		/* Create socket for found family */		
		s = socket(p->ai_family, p->ai_socktype, 0);

		if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
			errorPrint("Error in setsockopt: %s", strerror(errno)); /* maybe not so fatal, continue */
		}
		if (p->ai_family == AF_INET6) {
			if (setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) {
				errorPrint("Error in setsockopt: %s", strerror(errno));
			}
		}

		/* RTFM: getnameinfo */
		getnameinfo(p->ai_addr,
				p->ai_addrlen,
				dst,
				sizeof(dst),
				service,
				sizeof(service),
				NI_NUMERICHOST | NI_NUMERICSERV);

		infoPrint("Trying %s:%s ... ",dst, service);

		/* Try to bind socket */
		if (bind(s, p->ai_addr, p->ai_addrlen) == 0) {
			if (listen(s, 1) < 0) {
				errorPrint("listen failed: %s", strerror(errno));
				close(s);
			} else 	{
				infoPrint("bind successful");
				sockets[numsockets++] = s;
			}
		} else {
			errorPrint("bind failed: %s", strerror(errno));
			close(s);
		}

		p = p->ai_next;
	}

	freeaddrinfo(addr_info);
	infoPrint("Waiting for connections...");
	accept_loop(sockets, numsockets);
	for (i=0; i<numsockets; i++) {
		close(sockets[i]);
	}
	return 0;
}
Ejemplo n.º 5
0
int main (int argc, char **argv)
{
    struct sigaction sa;

    setProgName(argv[0]);

    FD_ZERO(&activeSet);
    FD_ZERO(&readSet);
    FD_ZERO(&writeSet);

    setFdUsed(stdinfd, DATA_INPUT_STREAM);
    outputIdx = setFdUsed(stdoutfd, DATA_OUTPUT_STREAM);

    while (argc > 1)
    {
        if (strcasecmp(argv[1], "-d") == 0)
        {
            setLogLevel(LOGLEVEL_DEBUG);
            debug = 1;
        }
        else if (strcasecmp(argv[1], "-q") == 0)
        {
            setLogLevel(LOGLEVEL_ERROR);
        }
        else if (strcasecmp(argv[1], "-o") == 0)
        {
            outputIdx = setFdUsed(stdoutfd, DATA_OUTPUT_COPY);
        }
        else if (strcasecmp(argv[1], "-r") == 0)
        {
            outputIdx = setFdUsed(stdoutfd, DATA_OUTPUT_SINK);
        }
        else if (strcasecmp(argv[1], "--src-filter") == 0 && argc > 2)
        {
            srcFilter = argv[2];
            argc--, argv++;
        }
        else if (strcasecmp(argv[1], "--rate-limit") == 0)
        {
            rateLimit = true;
        }
        else if (strcasecmp(argv[1], "-p") == 0 && argc > 2)
        {
            unsigned int uPort;

            if (sscanf(argv[2], "%u", &uPort))
            {
                port = (uint16_t) uPort;
            }
            argc--, argv++;
        }
        else
        {
            fprintf(stderr, "usage: n2kd [-d] [-q] [-o] [-r] [--src-filter <srclist>] [--rate-limit] [-p <port>]\n\n"
                    "  -d                      debug mode\n"
                    "  -q                      quiet mode\n"
                    "  -o                      output mode, send all TCP client data to stdout (as well as stdin)\n"
                    "  -r                      restrict mode, send no data to stdout\n"
                    "  --src-filter <srclist>  restrict NMEA0183 stream to particular N2K sources\n"
                    "  --rate-limit            restrict NMEA0183 stream to one message per source per second\n"
                    "  -p <port>               Start servers at <port> instead of 2597\n\n"
                    COPYRIGHT);
            exit(1);
        }
        argc--, argv++;
    }

    startTcpServers();

    /*  Ignore SIGPIPE, this will let a write to a socket that's closed   */
    /*  at the other end just fail instead of raising SIGPIPE             */
    memset( &sa, 0, sizeof( sa ) );
    sa.sa_handler = SIG_IGN;
    sigaction( SIGPIPE, &sa, 0 );

    doServerWork();

    exit(0);
}
Ejemplo n.º 6
0
int main (int argc, char **argv)
{
  struct sigaction sa;

  setProgName(argv[0]);

  FD_ZERO(&activeSet);
  FD_ZERO(&readSet);
  FD_ZERO(&writeSet);

  setFdUsed(stdinfd, DATA_INPUT_STREAM);
  outputIdx = setFdUsed(stdoutfd, DATA_OUTPUT_STREAM);

  while (argc > 1)
  {
    if (strcasecmp(argv[1], "-d") == 0)
    {
      setLogLevel(LOGLEVEL_DEBUG);
    }
    else if (strcasecmp(argv[1], "-q") == 0)
    {
      setLogLevel(LOGLEVEL_ERROR);
    }
    else if (strcasecmp(argv[1], "-o") == 0)
    {
      outputIdx = setFdUsed(stdoutfd, DATA_OUTPUT_COPY);
    }
    else if (strcasecmp(argv[1], "-r") == 0)
    {
      outputIdx = setFdUsed(stdoutfd, DATA_OUTPUT_SINK);
    }
    else if (strcasecmp(argv[1], "--src-filter") == 0 && argc > 2)
    {
      srcFilter = argv[2];
      argc--, argv++;
    }
    else if (strcasecmp(argv[1], "-p") == 0 && argc > 2)
    {
      unsigned int uPort;

      if (sscanf(argv[2], "%u", &uPort))
      {
        port = (uint16_t) uPort;
      }
      argc--, argv++;
    }
    else
    {
      fprintf(stderr, "usage: n2kd [-d] [-q] [--src-filter <srclist>] [-o] [-p <port>] [-r]\n\n"COPYRIGHT);
      exit(1);
    }
    argc--, argv++;
  }

  startTcpServers();

  /*  Ignore SIGPIPE, this will let a write to a socket that's closed   */
  /*  at the other end just fail instead of raising SIGPIPE             */
  memset( &sa, 0, sizeof( sa ) );
  sa.sa_handler = SIG_IGN;
  sigaction( SIGPIPE, &sa, 0 );

  doServerWork();

  exit(0);
}
Ejemplo n.º 7
0
/**  Start des Servers
 *   param argc Anzahl der Startparameter
 *   param argv Startparameter
 */
int main(int argc, char ** argv) {

	// Der Server soll auf dem lokalen System nur einmal gestartet werden koennen.
	setSingleInstance(SingleInstanceFile);

	setProgName(argv[0]);

	// verarbeite Parameter
	process_commands(argc, argv);

	// reagiere auf Signal, u.a. STRG + C
	signal(SIGINT, INThandler);

	// gebe Gruppennamen aus
	infoPrint("\n\nServer Gruppe 04 Stroh, Steinbinder, Strohm\n");

	// Spielerverwaltung initialisieren
	initSpielerverwaltung();

	// Socket erstellen
	server_socket = openServerSocket(server_port);
	if(server_socket == -1){
		errorPrint("Server Socket konnte nicht erstellt werden!");
		endServer();
		exit(0);
	}

	// Loader starten + Kataloge laden
	int loader_start_result = startLoader();
	if(loader_start_result != 0){
		errorPrint("Fehler beim Starten des Loaders: %i", loader_start_result);
		endServer();
		exit(0);
	}
	int loader_load_catalogs_result = loadCatalogs();
	if(loader_load_catalogs_result != 0){
		errorPrint("Fehler beim Laden der Kataloge: %i", loader_load_catalogs_result);
		endServer();
		exit(0);
	}

	// http://pubs.opengroup.org/onlinepubs/7908799/xsh/sem_init.html
	// Semaphor fuer Spielerliste / Punktestand initialisieren
	sem_init(&semaphor_score, 0, 0);

	// Score thread starten
	pthread_t score_thread;
	if(pthread_create(&score_thread, NULL, (void*)&score_main, NULL) == -1){
		errorPrint("Score_thread konnte nicht erstellt werden!");
		endServer();
		exit(0);
	}

	// starte Login-Thread
	pthread_t login_thread;
	if(pthread_create(&login_thread, NULL, (void*)login_main(server_socket), NULL) == -1){
		errorPrint("Login_thread konnte nicht erstellt werden!");
		endServer();
		exit(0);
	}

	// beende Server
	endServer();
	return 0;
}
Ejemplo n.º 8
0
/*
 * Hauptprogramm des Servers
 */
int main(int argc, char **argv)
{
	unsigned short port = 54321;
	argc_cp = argc;
	argv_cp = argv;
	pid_t forkResult;
	char pfad[51];
	char catalog[51];

	/*
	 * Semaphore initialisieren
	 */
	sem_init(&uno_semaphore, 0, 0);


	set_pid();
	if(detect_para(&port, pfad, catalog) == -1)
	{
		exit(0);
	}

	/*
	 *Verhalten des Servers bei Strg+C
	 */
	signal(SIGINT,sigfunc);


	infoPrint("gewählter Port: %d", port);
	infoPrint("gewählter Pfad: %s", pfad);
	infoPrint("gewählter Katalog: %s", catalog);
	/*
	 *Den Programmnamen setzen
	 */
	setProgName(argv[0]);

	infoPrint("Server Gruppe 6/n");
	infoPrint("Info: Der Server kann mit STRG-C beendet werden.");
	infoPrint("--------------------------------------------------------------------------------------------------------------\n");
	
	/*
	 *Socket erstellen
	 */
	start_network(port);

	/*
	 *Pipe erstellen
	 */
	if(pipe(stdinPipe) == -1 || pipe(stdoutPipe) == -1)
	{
		perror("pipe");
	}

	/*
	 *Kindprozess erstellen
	 */
	forkResult = fork();
	if(forkResult < 0)
	{
		perror("fork");
	}
	/*
	 *Im Kindprozess
	 */
	else if(forkResult == 0)
	{	/*
	 	 *Standardeingabekanal mit dem Pipekanal stdinPipe[0] verbinden
	 	 */
		if(dup2(stdinPipe[0], STDIN_FILENO) == -1)
		{
		  perror("dup2(stdinPipe[0], STDIN_FILENO)");
		}

		/*Standardausgabekanal mit dem Pipekanal stdinPipe[1] verbinden*/
		if(dup2(stdoutPipe[1], STDOUT_FILENO) == -1)				{
		  perror("dup2(stdoutPipe[1], STDOUT_FILENO)");
		}

		/* Schließen aller Pipe-Deskriptoren.
		* Nach dem exec kennt der Kindprozess diese nicht mehr und spricht
		* die Pipes selbst über stdin und stdout an.
		*/
		close(stdinPipe[0]); close(stdinPipe[1]);
		close(stdoutPipe[0]); close(stdoutPipe[1]);

		/*
		 *Neues Programm läuft...
		 */
		execl("./loader", "loader", "-d", catalog, NULL);
		/*
		 * ...oder auch nicht, dann war's aber ein Fehler
		 */
		perror("exec");
	}

	close(stdinPipe[0]);
	close(stdoutPipe[1]);

	pthread_t login_thread_id;

	/*
	 *Login Thread starten
	 */
	if((pthread_create(&login_thread_id, 0, (void*)&login_loop, &socket_desc)) != 0)
	{
		perror("Thread_create steht in main.c");
	}

	pthread_t spielstand_thread_id;
	infoPrint("NACH LOGIN!!!");

	/*
	 *Spielstand Thread starten
	 */
	if((pthread_create(&spielstand_thread_id, NULL, (void*)&spielstand_thread_main, NULL)) != 0)
	{
		perror("Thread_create steht in main.c");
	}

	/*
	 * Warten auf das Ende des Spielstandthreads
	 */
	pthread_join(spielstand_thread_id, 0);
	/*
	 *Server beenden
	 */
	quitServer(NO_ERROR, 0);
	return 0;
}
Ejemplo n.º 9
0
void
setupRtsFlags(int *argc, char *argv[], int *rts_argc, char *rts_argv[])
{
    rtsBool error = rtsFalse;
    I_ mode;
    I_ arg, total_arg;

    setProgName (argv);
    total_arg = *argc;
    arg = 1;

    *argc = 1;
    *rts_argc = 0;

    // process arguments from the ghc_rts_opts global variable first.
    // (arguments from the GHCRTS environment variable and the command
    // line override these).
    {
	if (ghc_rts_opts != NULL) {
	    splitRtsFlags(ghc_rts_opts, rts_argc, rts_argv);
	}
    }

    // process arguments from the GHCRTS environment variable next
    // (arguments from the command line override these).
    {
	char *ghc_rts = getenv("GHCRTS");

	if (ghc_rts != NULL) {
            if (rtsOptsEnabled != rtsOptsNone) {
                splitRtsFlags(ghc_rts, rts_argc, rts_argv);
            }
            else {
                errorBelch("Warning: Ignoring GHCRTS variable as RTS options are disabled.\n         Link with -rtsopts to enable them.");
                // We don't actually exit, just warn
            }
	}
    }

    // Split arguments (argv) into PGM (argv) and RTS (rts_argv) parts
    //   argv[0] must be PGM argument -- leave in argv

    for (mode = PGM; arg < total_arg; arg++) {
	// The '--RTS' argument disables all future +RTS ... -RTS processing.
	if (strequal("--RTS", argv[arg])) {
	    arg++;
	    break;
	}
	// The '--' argument is passed through to the program, but
	// disables all further +RTS ... -RTS processing.
	else if (strequal("--", argv[arg])) {
	    break;
	}
	else if (strequal("+RTS", argv[arg])) {
            if (rtsOptsEnabled != rtsOptsNone) {
                mode = RTS;
            }
            else {
                errorBelch("RTS options are disabled. Link with -rtsopts to enable them.");
                stg_exit(EXIT_FAILURE);
            }
	}
	else if (strequal("-RTS", argv[arg])) {
	    mode = PGM;
	}
	else if (mode == RTS && *rts_argc < MAX_RTS_ARGS-1) {
            rts_argv[(*rts_argc)++] = argv[arg];
        }
        else if (mode == PGM) {
	    argv[(*argc)++] = argv[arg];
	}
	else {
	  barf("too many RTS arguments (max %d)", MAX_RTS_ARGS-1);
	}
    }
    // process remaining program arguments
    for (; arg < total_arg; arg++) {
	argv[(*argc)++] = argv[arg];
    }
    argv[*argc] = (char *) 0;
    rts_argv[*rts_argc] = (char *) 0;

    // Process RTS (rts_argv) part: mainly to determine statsfile
    for (arg = 0; arg < *rts_argc; arg++) {
	if (rts_argv[arg][0] != '-') {
	    fflush(stdout);
	    errorBelch("unexpected RTS argument: %s", rts_argv[arg]);
	    error = rtsTrue;

        } else {

            switch(rts_argv[arg][1]) {
            case '-':
                if (strequal("info", &rts_argv[arg][2])) {
                    printRtsInfo();
                    stg_exit(0);
                }
                break;
            default:
                break;
            }

            if (rtsOptsEnabled != rtsOptsAll)
            {
                errorBelch("Most RTS options are disabled. Link with -rtsopts to enable them.");
                stg_exit(EXIT_FAILURE);
            }

            switch(rts_argv[arg][1]) {

	      /* process: general args, then PROFILING-only ones, then
		 CONCURRENT-only, TICKY-only (same order as defined in
		 RtsFlags.lh); within those groups, mostly in
		 case-insensitive alphabetical order.  Final group is
		 x*, which allows for more options.
	      */

#ifdef TICKY_TICKY
# define TICKY_BUILD_ONLY(x) x
#else
# define TICKY_BUILD_ONLY(x) \
errorBelch("the flag %s requires the program to be built with -ticky", rts_argv[arg]); \
error = rtsTrue;
#endif

#ifdef PROFILING
# define PROFILING_BUILD_ONLY(x)   x
#else
# define PROFILING_BUILD_ONLY(x) \
errorBelch("the flag %s requires the program to be built with -prof", rts_argv[arg]); \
error = rtsTrue;
#endif

#ifdef TRACING
# define TRACING_BUILD_ONLY(x)   x
#else
# define TRACING_BUILD_ONLY(x) \
errorBelch("the flag %s requires the program to be built with -eventlog or -debug", rts_argv[arg]); \
error = rtsTrue;
#endif

#ifdef THREADED_RTS
# define THREADED_BUILD_ONLY(x)      x
#else
# define THREADED_BUILD_ONLY(x) \
errorBelch("the flag %s requires the program to be built with -threaded", rts_argv[arg]); \
error = rtsTrue;
#endif

#ifdef DEBUG
# define DEBUG_BUILD_ONLY(x) x
#else
# define DEBUG_BUILD_ONLY(x) \
errorBelch("the flag %s requires the program to be built with -debug", rts_argv[arg]); \
error = rtsTrue;
#endif

	      /* =========== GENERAL ========================== */
	      case '?':
		error = rtsTrue;
		break;

              /* This isn't going to allow us to keep related options
                 together as we add more --* flags. We really need a
                 proper options parser. */
	      case '-':
                  if (strequal("install-signal-handlers=yes",
                               &rts_argv[arg][2])) {
                      RtsFlags.MiscFlags.install_signal_handlers = rtsTrue;
                  }
                  else if (strequal("install-signal-handlers=no",
                               &rts_argv[arg][2])) {
                      RtsFlags.MiscFlags.install_signal_handlers = rtsFalse;
                  }
                  else if (strequal("machine-readable",
                               &rts_argv[arg][2])) {
                      RtsFlags.MiscFlags.machineReadable = rtsTrue;
                  }
                  else if (strequal("info",
                               &rts_argv[arg][2])) {
                      printRtsInfo();
                      stg_exit(0);
                  }
                  else {
		      errorBelch("unknown RTS option: %s",rts_argv[arg]);
		      error = rtsTrue;
                  }
		  break;
	      case 'A':
                  RtsFlags.GcFlags.minAllocAreaSize
                      = decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_INT_MAX)
                           / BLOCK_SIZE;
                  break;

#ifdef USE_PAPI
	      case 'a':
		switch(rts_argv[arg][2]) {
		case '1':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L1;
		  break;
		case '2':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_CACHE_L2;
		  break;
		case 'b':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_BRANCH;
		  break;
		case 's':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_STALLS;
		  break;
		case 'e':
		  RtsFlags.PapiFlags.eventType = PAPI_FLAG_CB_EVENTS;
		  break;
                case '+':
                case '#':
                  if (RtsFlags.PapiFlags.numUserEvents >= MAX_PAPI_USER_EVENTS) {
                      errorBelch("maximum number of PAPI events reached");
                      stg_exit(EXIT_FAILURE);
                  }
                  nat eventNum  = RtsFlags.PapiFlags.numUserEvents++;
                  char kind     = rts_argv[arg][2];
                  nat eventKind = kind == '+' ? PAPI_PRESET_EVENT_KIND : PAPI_NATIVE_EVENT_KIND;

                  RtsFlags.PapiFlags.userEvents[eventNum] = rts_argv[arg] + 3;
                  RtsFlags.PapiFlags.eventType = PAPI_USER_EVENTS;
                  RtsFlags.PapiFlags.userEventsKind[eventNum] = eventKind;
                  break;
		default:
		  bad_option( rts_argv[arg] );
		}
		break;
#endif

	      case 'B':
		RtsFlags.GcFlags.ringBell = rtsTrue;
		break;

	      case 'c':
		  if (rts_argv[arg][2] != '\0') {
		      RtsFlags.GcFlags.compactThreshold =
			  atof(rts_argv[arg]+2);
		  } else {
		      RtsFlags.GcFlags.compact = rtsTrue;
		  }
		  break;

              case 'w':
		RtsFlags.GcFlags.sweep = rtsTrue;
		break;

	      case 'F':
	        RtsFlags.GcFlags.oldGenFactor = atof(rts_argv[arg]+2);
	      
		if (RtsFlags.GcFlags.oldGenFactor < 0)
		  bad_option( rts_argv[arg] );
		break;
	      
	      case 'D':
              DEBUG_BUILD_ONLY(
	      { 
		  char *c;

		  for (c  = rts_argv[arg] + 2; *c != '\0'; c++) {
		      switch (*c) {
		      case 's':
			  RtsFlags.DebugFlags.scheduler = rtsTrue;
			  break;
		      case 'i':
			  RtsFlags.DebugFlags.interpreter = rtsTrue;
			  break;
		      case 'w':
			  RtsFlags.DebugFlags.weak = rtsTrue;
			  break;
		      case 'G':
			  RtsFlags.DebugFlags.gccafs = rtsTrue;
			  break;
		      case 'g':
			  RtsFlags.DebugFlags.gc = rtsTrue;
			  break;
		      case 'b':
			  RtsFlags.DebugFlags.block_alloc = rtsTrue;
			  break;
		      case 'S':
			  RtsFlags.DebugFlags.sanity = rtsTrue;
			  break;
		      case 't':
			  RtsFlags.DebugFlags.stable = rtsTrue;
			  break;
		      case 'p':
			  RtsFlags.DebugFlags.prof = rtsTrue;
			  break;
		      case 'l':
			  RtsFlags.DebugFlags.linker = rtsTrue;
			  break;
		      case 'a':
			  RtsFlags.DebugFlags.apply = rtsTrue;
			  break;
		      case 'm':
			  RtsFlags.DebugFlags.stm = rtsTrue;
			  break;
		      case 'z':
			  RtsFlags.DebugFlags.squeeze = rtsTrue;
			  break;
		      case 'c':
			  RtsFlags.DebugFlags.hpc = rtsTrue;
			  break;
		      case 'r':
			  RtsFlags.DebugFlags.sparks = rtsTrue;
			  break;
		      default:
			  bad_option( rts_argv[arg] );
		      }
		  }
                  // -Dx also turns on -v.  Use -l to direct trace
                  // events to the .eventlog file instead.
                  RtsFlags.TraceFlags.tracing = TRACE_STDERR;
	      })
              break;

	      case 'K':
                  RtsFlags.GcFlags.maxStkSize =
                      decodeSize(rts_argv[arg], 2, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;

	      case 'k':
		switch(rts_argv[arg][2]) {
                case 'c':
                  RtsFlags.GcFlags.stkChunkSize =
                      decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;
                case 'b':
                  RtsFlags.GcFlags.stkChunkBufferSize =
                      decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;
                case 'i':
                  RtsFlags.GcFlags.initialStkSize =
                      decodeSize(rts_argv[arg], 3, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;
                default:
                  RtsFlags.GcFlags.initialStkSize =
                      decodeSize(rts_argv[arg], 2, sizeof(W_), HS_WORD_MAX) / sizeof(W_);
                  break;
                }
                break;

              case 'M':
                  RtsFlags.GcFlags.maxHeapSize =
                      decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_WORD_MAX) / BLOCK_SIZE;
                  /* user give size in *bytes* but "maxHeapSize" is in *blocks* */
                  break;

	      case 'm':
                  RtsFlags.GcFlags.pcFreeHeap = atof(rts_argv[arg]+2);

                  if (RtsFlags.GcFlags.pcFreeHeap < 0 ||
                      RtsFlags.GcFlags.pcFreeHeap > 100)
                      bad_option( rts_argv[arg] );
                  break;

	      case 'G':
                  RtsFlags.GcFlags.generations =
                      decodeSize(rts_argv[arg], 2, 1, HS_INT_MAX);
                  break;

	      case 'H':
                  if (rts_argv[arg][2] == '\0') {
                      RtsFlags.GcFlags.heapSizeSuggestionAuto = rtsTrue;
                  } else {
                      RtsFlags.GcFlags.heapSizeSuggestion =
                          (nat)(decodeSize(rts_argv[arg], 2, BLOCK_SIZE, HS_WORD_MAX) / BLOCK_SIZE);
                  }
                  break;

#ifdef RTS_GTK_FRONTPANEL
	      case 'f':
		  RtsFlags.GcFlags.frontpanel = rtsTrue;
		  break;
#endif

    	      case 'I':	/* idle GC delay */
		if (rts_argv[arg][2] == '\0') {
		  /* use default */
		} else {
		    I_ cst; /* tmp */

		    /* Convert to millisecs */
		    cst = (I_) ((atof(rts_argv[arg]+2) * 1000));
		    RtsFlags.GcFlags.idleGCDelayTime = cst;
		}
		break;

	      case 'S':
		  RtsFlags.GcFlags.giveStats = VERBOSE_GC_STATS;
		  goto stats;

	      case 's':
		  RtsFlags.GcFlags.giveStats = SUMMARY_GC_STATS;
		  goto stats;

	      case 't':
		  RtsFlags.GcFlags.giveStats = ONELINE_GC_STATS;
		  goto stats;

	    stats:
		{ 
		    int r;
		    r = open_stats_file(arg, *argc, argv,
					*rts_argc, rts_argv, NULL,
					&RtsFlags.GcFlags.statsFile);
		    if (r == -1) { error = rtsTrue; }
		}
                break;

	      case 'Z':
		RtsFlags.GcFlags.squeezeUpdFrames = rtsFalse;
		break;

	      /* =========== PROFILING ========================== */

	      case 'P': /* detailed cost centre profiling (time/alloc) */
	      case 'p': /* cost centre profiling (time/alloc) */
		PROFILING_BUILD_ONLY(
		switch (rts_argv[arg][2]) {
		  case 'x':
		    RtsFlags.CcFlags.doCostCentres = COST_CENTRES_XML;
		    break;
		  case 'a':
		    RtsFlags.CcFlags.doCostCentres = COST_CENTRES_ALL;
		    break;
		  default:
		      if (rts_argv[arg][1] == 'P') {
			  RtsFlags.CcFlags.doCostCentres =
			      COST_CENTRES_VERBOSE;
		      } else {
			  RtsFlags.CcFlags.doCostCentres =
			      COST_CENTRES_SUMMARY;
		      }
		      break;
		}
		) break;

	      case 'R':
		  PROFILING_BUILD_ONLY(
		      RtsFlags.ProfFlags.maxRetainerSetSize = atof(rts_argv[arg]+2);
  	          ) break;
	      case 'L':
		  PROFILING_BUILD_ONLY(
		      RtsFlags.ProfFlags.ccsLength = atof(rts_argv[arg]+2);
                      if(RtsFlags.ProfFlags.ccsLength <= 0) {
			bad_option(rts_argv[arg]);
                      }
		  ) break;
Ejemplo n.º 10
0
int main(int argc, char **argv)
{
  int            r;
  int            handle;
  struct termios attr;
  char *         name   = argv[0];
  char *         device = 0;
  struct stat    statbuf;
  int            pid = 0;
  int            speed;

  setProgName(argv[0]);
  while (argc > 1)
  {
    if (strcasecmp(argv[1], "-version") == 0)
    {
      printf("%s\n", VERSION);
      exit(0);
    }
    else if (strcasecmp(argv[1], "-w") == 0)
    {
      writeonly = 1;
    }
    else if (strcasecmp(argv[1], "-p") == 0)
    {
      passthru = 1;
    }
    else if (strcasecmp(argv[1], "-r") == 0)
    {
      readonly = 1;
    }
    else if (strcasecmp(argv[1], "-v") == 0)
    {
      verbose = 1;
    }
    else if (strcasecmp(argv[1], "-t") == 0 && argc > 2)
    {
      argc--;
      argv++;
      timeout = strtol(argv[1], 0, 10);
      logDebug("timeout set to %ld seconds\n", timeout);
    }
    else if (strcasecmp(argv[1], "-s") == 0 && argc > 2)
    {
      argc--;
      argv++;
      speed = strtol(argv[1], 0, 10);
      switch (speed)
      {
        case 38400:
          baudRate = B38400;
          break;
        case 57600:
          baudRate = B57600;
          break;
        case 115200:
          baudRate = B115200;
          break;
        case 230400:
          baudRate = B230400;
          break;
#ifdef B460800
        case 460800:
          baudRate = B460800;
          break;
#endif
#ifdef B921600
        case 921600:
          baudRate = B921600;
          break;
#endif
        default:
          baudRate = speed;
          break;
      }
      logDebug("speed set to %d (%d) baud\n", speed, baudRate);
    }
    else if (strcasecmp(argv[1], "-d") == 0)
    {
      setLogLevel(LOGLEVEL_DEBUG);
    }
    else if (strcasecmp(argv[1], "-o") == 0)
    {
      outputCommands = 1;
    }
    else if (!device)
    {
      device = argv[1];
    }
    else
    {
      device = 0;
      break;
    }
    argc--;
    argv++;
  }

  if (!device)
  {
    fprintf(stderr,
            "Usage: %s [-w] -[-p] [-r] [-v] [-d] [-s <n>] [-t <n>] device\n"
            "\n"
            "Options:\n"
            "  -w      writeonly mode, no data is read from device\n"
            "  -r      readonly mode, no data is sent to device\n"
            "  -p      passthru mode, data on stdin is sent to stdout but not to device\n"
            "  -v      verbose\n"
            "  -d      debug\n"
            "  -s <n>  set baudrate to 38400, 57600, 115200, 230400"
#ifdef B460800
            ", 460800"
#endif
#ifdef B921600
            ", 921600"
#endif
            "\n"
            "  -t <n>  timeout, if no message is received after <n> seconds the program quits\n"
            "  -o      output commands sent to stdin to the stdout \n"
            "  <device> can be a serial device, a normal file containing a raw log,\n"
            "  or the address of a TCP server in the format tcp://<host>[:<port>]\n"
            "\n"
            "  Examples: %s /dev/ttyUSB0\n"
            "            %s tcp://192.168.1.1:10001\n"
            "\n" COPYRIGHT,
            name,
            name,
            name);
    exit(1);
  }

retry:
  logDebug("Opening %s\n", device);
  if (strncmp(device, "tcp:", STRSIZE("tcp:")) == 0)
  {
    handle = open_socket_stream(device);
    logDebug("socket = %d\n", handle);
    isFile = true;
    if (handle < 0)
    {
      fprintf(stderr, "Cannot open NGT-1-A TCP stream %s\n", device);
      exit(1);
    }
  }
  else
  {
    handle = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
    logDebug("fd = %d\n", handle);
    if (handle < 0)
    {
      logAbort("Cannot open NGT-1-A device %s\n", device);
    }
    if (fstat(handle, &statbuf) < 0)
    {
      logAbort("Cannot determine device %s\n", device);
    }
    isFile = S_ISREG(statbuf.st_mode);
  }

  if (isFile)
  {
    logInfo("Device is a normal file, do not set the attributes.\n");
  }
  else
  {
    logDebug("Device is a serial port, set the attributes.\n");

    memset(&attr, 0, sizeof(attr));
    if (cfsetspeed(&attr, baudRate) < 0)
    {
      logAbort("Could not set baudrate %d\n", speed);
    }
    attr.c_cflag |= CS8 | CLOCAL | CREAD;

    attr.c_iflag |= IGNPAR;
    attr.c_cc[VMIN]  = 1;
    attr.c_cc[VTIME] = 0;
    tcflush(handle, TCIFLUSH);
    tcsetattr(handle, TCSANOW, &attr);

    logDebug("Device is a serial port, send the startup sequence.\n");

    writeMessage(handle, NGT_MSG_SEND, NGT_STARTUP_SEQ, sizeof(NGT_STARTUP_SEQ));
    sleep(2);
  }

  for (;;)
  {
    unsigned char msg[BUFFER_SIZE];
    size_t        msgLen;
    int           r = isReady(writeonly ? INVALID_SOCKET : handle, readonly ? INVALID_SOCKET : 0, INVALID_SOCKET, timeout);

    if ((r & FD1_ReadReady) > 0)
    {
      if (!readNGT1(handle))
      {
        break;
      }
    }
    if ((r & FD2_ReadReady) > 0)
    {
      if (!readIn(msg, sizeof(msg)))
      {
        break;
      }
      if (!passthru)
      {
        parseAndWriteIn(handle, msg);
      }
      if (outputCommands)
      {
        fprintf(stdout, "%s", msg);
        fflush(stdout);
      }
    }
    else if (writeonly)
    {
      break;
    }
  }

  close(handle);
  return 0;
}
Ejemplo n.º 11
0
int main(int argc, char ** argv)
{
  int r;
  int handle;
  struct termios attr;
  char * device = 0;
  struct stat statbuf;
  int pid = 0;

  setProgName(argv[0]);

  while (argc > 1)
  {
    if (strcasecmp(argv[1], "-r") == 0)
    {
      readonly = 1;
    }
    else if (strcasecmp(argv[1], "-d") == 0)
    {
      setLogLevel(LOGLEVEL_DEBUG);
    }
    else if (strcasecmp(argv[1], "-?") == 0)
    {
      break;
    }
    else if (!device)
    {
      device = argv[1];
    }
    else
    {
      device = 0;
      break;
    }
    argc--;
    argv++;
  }

  if (!device)
  {
    fprintf(stderr, "Usage: nmea0183-serial [-r] [-d] device\n\n"
    "-r : read-only, do not pass stdin to stdout\n"
    "-d : debug mode\n\n"
    "Example: nmea0183-serial /dev/ttyUSB0\n\n"COPYRIGHT);
    exit(1);
  }

retry:
  logDebug("Opening %s\n", device);
  handle = open(device, O_RDWR | O_NOCTTY);
  logDebug("fd = %d\n", handle);
  if (handle < 0)
  {
    logAbort("NMEA-00001: Cannot open NMEA-0183 device %s\n", device);
    exit(1);
  }
  if (fstat(handle, &statbuf) < 0)
  {
    logAbort("NMEA-00002: Cannot determine device %s\n", device);
    exit(1);
  }
  isFile = S_ISREG(statbuf.st_mode);

  if (!isFile)
  {
    logDebug("Device is a serial port, set the attributes.\n");

    memset(&attr, 0, sizeof(attr));
    attr.c_cflag = B38400 | CS8 | CLOCAL | CREAD;
    attr.c_iflag = IGNPAR;
    attr.c_oflag = 0;
    attr.c_lflag = 0;
    attr.c_cc[VMIN] = 0;
    attr.c_cc[VTIME] = 1;
    tcflush(handle, TCIFLUSH);
    tcsetattr(handle, TCSANOW, &attr);
  }

  for (;;)
  {
    char msg[BUFFER_SIZE];
    size_t msgLen;
    enum ReadyDescriptor r;
    int b;

    r = isready(handle, readonly ? -1 : 0);

    if ((r & FD1_Ready) > 0)
    {
      b = read(handle, msg, sizeof(msg));
      if (b < 0)
      {
        break;
      }
      else if (b > 0)
      {
        if (write(1, msg, b) < b)
        {
          break;
        }
      }
    }
    if ((r & FD2_Ready) > 0)
    {
      b = read(0, msg, sizeof(msg));
      if (b < 0)
      {
        break;
      }
      else if (b > 0)
      {
        if (write(1, msg, b) < b)
        {
          break;
        }
        if (write(handle, msg, b) < b)
        {
          break;
        }
      }
    }
  }

  close(handle);
  return 0;
}
Ejemplo n.º 12
0
int main(int argc, char ** argv)
{
  int r;
  int handle;
  struct termios attr;
  char * name = argv[0];
  char * device = 0;
  struct stat statbuf;
  int pid = 0;

  setProgName(argv[0]);
  while (argc > 1)
  {
    if (strcasecmp(argv[1], "-w") == 0)
    {
      writeonly = 1;
    }
    else if (strcasecmp(argv[1], "-p") == 0)
    {
      passthru = 1;
    }
    else if (strcasecmp(argv[1], "-r") == 0)
    {
      readonly = 1;
    }
    else if (strcasecmp(argv[1], "-v") == 0)
    {
      verbose = 1;
    }
    else if (strcasecmp(argv[1], "-t") == 0 && argc > 2)
    {
      argc--;
      argv++;
      timeout = strtol(argv[1], 0, 10);
      logDebug("timeout set to %ld seconds\n", timeout);
    }
    else if (strcasecmp(argv[1], "-d") == 0)
    {
      debug = 1;
      setLogLevel(LOGLEVEL_DEBUG);
    }
    else if (!device)
    {
      device = argv[1];
    }
    else
    {
      device = 0;
      break;
    }
    argc--;
    argv++;
  }

  if (!device)
  {
    fprintf(stderr, 
    "Usage: %s [-w] -[-p] [-r] [-v] [-d] [-t <n>] device\n"
    "\n"
    "Options:\n"
    "  -w      writeonly mode, no data is read from device\n"
    "  -r      readonly mode, no data is sent to device\n"
    "  -p      passthru mode, data on stdin is sent to stdout but not to device\n"
    "  -v      verbose\n"
    "  -d      debug\n"
    "  -t <n>  timeout, if no message is received after <n> seconds the program quits\n"
    "  <device> can be a serial device, a normal file containing a raw log,\n"
    "  or the address of a TCP server in the format tcp://<host>[:<port>]\n"
    "\n" 
    "  Examples: %s /dev/ttyUSB0\n"
    "            %s tcp://192.168.1.1:10001\n"
    "\n" 
    COPYRIGHT, name, name, name);
    exit(1);
  }

retry:
  if (debug) fprintf(stderr, "Opening %s\n", device);
  if (strncmp(device, "tcp:", STRSIZE("tcp:")) == 0)
  {
    handle = open_socket_stream(device);
    if (debug) fprintf(stderr, "socket = %d\n", handle);
    isFile = true;
    if (handle < 0)
    {
      fprintf(stderr, "Cannot open NGT-1-A TCP stream %s\n", device);
      exit(1);
    }
  }
  else
  {
    handle = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (debug) fprintf(stderr, "fd = %d\n", handle);
    if (handle < 0)
    {
      fprintf(stderr, "Cannot open NGT-1-A device %s\n", device);
      exit(1);
    }
    if (fstat(handle, &statbuf) < 0)
    {
      fprintf(stderr, "Cannot determine device %s\n", device);
      exit(1);
    }
    isFile = S_ISREG(statbuf.st_mode);
  }

  if (isFile)
  {
    if (debug) fprintf(stderr, "Device is a normal file, do not set the attributes.\n");
  }
  else
  {
    if (debug) fprintf(stderr, "Device is a serial port, set the attributes.\n");

    memset(&attr, 0, sizeof(attr));
    cfsetispeed(&attr, B115200);
    cfsetospeed(&attr, B115200);
    attr.c_cflag |= CS8 | CLOCAL | CREAD;

    attr.c_iflag |= IGNPAR;
    attr.c_cc[VMIN] = 1;
    attr.c_cc[VTIME] = 0;
    tcflush(handle, TCIFLUSH);
    tcsetattr(handle, TCSANOW, &attr);

    if (debug) fprintf(stderr, "Device is a serial port, send the startup sequence.\n");

    writeMessage(handle, NGT_MSG_SEND, NGT_STARTUP_SEQ, sizeof(NGT_STARTUP_SEQ));
    sleep(2);
  }

  for (;;)
  {
    unsigned char msg[BUFFER_SIZE];
    size_t msgLen;
    enum ReadyDescriptor r;

    r = isready(writeonly ? -1 : handle, readonly ? -1 : 0);

    if ((r & FD1_Ready) > 0)
    {
      if (!readNGT1(handle))
      {
        break;
      }
    }
    if ((r & FD2_Ready) > 0)
    {
      if (!readIn(msg, sizeof(msg)))
      {
        break;
      }
      if (!passthru)
      {
        parseAndWriteIn(handle, msg);
      }
      fprintf(stdout, "%s", msg);
      fflush(stdout);
    }
    else if (writeonly)
    {
      break;
    }
  }

  close(handle);
  return 0;
}