示例#1
0
void on_select(CassFuture* future, void* data) {
  CassError code = cass_future_error_code(future);
  if (code != CASS_OK) {
    print_error(future);
  } else {
    const CassResult* result = cass_future_get_result(future);
    CassIterator* iterator = cass_iterator_from_result(result);
    while (cass_iterator_next(iterator)) {
      CassUuid key;
      char key_str[CASS_UUID_STRING_LENGTH];
      cass_uint64_t value = 0;
      const CassRow* row = cass_iterator_get_row(iterator);

      cass_value_get_uuid(cass_row_get_column(row, 0), &key);

      cass_uuid_string(key, key_str);
      cass_value_get_int64(cass_row_get_column(row, 1), (cass_int64_t*)&value);

      printf("%s, %llu\n", key_str, (unsigned long long)value);
    }
    cass_iterator_free(iterator);
    cass_result_free(result);
  }

  signal_exit((CassSession*)data);
}
示例#2
0
static
void term_sighandler(int sig_num)
{
  printf("We caught signal %d\n", sig_num);
  signal_exit();
  printf("exiting\n");
  exit(1);
}
void signal_termination_handler(  //The real signal
                                int sig) {
  printf ("Signal_termination_handler called with signal %d\n", sig);
  switch (sig) {
    case SIGABRT:
      signal_exit (-1);          //use abort code
      //         case SIGBUS:
    case SIGSEGV:
      signal_exit (0);
    case SIGFPE:
      signal_exit (1);           //floating point
    case SIGTERM:
      signal_exit (2);           //timeout by cmdtimer
    default:
      signal_exit (3);           //Anything else
  }
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
DEFINE_THREAD_ROUTINE(directx_renderer_thread, data)
{
    HWND hWnd = NULL;
	
	WNDCLASSEX wc =
	{
		sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L,
		GetModuleHandle( NULL ), NULL, NULL, NULL, NULL,
		L"A.R.Drone Video", NULL
	};
	RegisterClassEx( &wc );

	if (data == NULL)
	{
		// Create the application's window
		hWnd = CreateWindow( L"A.R.Drone Video", L"A.R.Drone Video",
								  WS_OVERLAPPEDWINDOW, 100, 100, 640, 480,
								  NULL, NULL, wc.hInstance, NULL );
	}
	else
	{
		hWnd = (HWND)data;
	}

    // Initialize Direct3D
    if( SUCCEEDED( InitD3D( hWnd ) ) )
    {
        // Create the scene geometry
        if( SUCCEEDED( InitGeometry() ) )
        {
            // Show the window
            ShowWindow( hWnd, SW_SHOWDEFAULT );
            UpdateWindow( hWnd );

            // Enter the message loop
            MSG msg;
            ZeroMemory( &msg, sizeof( msg ) );
            while( msg.message != WM_QUIT )
            {
                if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
                {
                    TranslateMessage( &msg );
                    DispatchMessage( &msg );
                }
                else
                    Render();
            }
        }
    }
	
	UnregisterClass( L"A.R.Drone Video", wc.hInstance );

	/* Tells ARDRoneTool to shutdown */
	signal_exit();

    return 0;
}
示例#5
0
void controlCHandler (int signal)
{
#if CONTROL_C_HANDLER_USES_ARDRONE_TOOL_EXIT
    gtk_main_quit ();
    signal_exit ();
#else
    // Flush all streams before terminating
    fflush (NULL);
    usleep (200000); // Wait 200 msec to be sure that flush occured
    printf ("\nAll files were flushed\n");
    exit (0);
#endif
}
示例#6
0
void on_session_connect(CassFuture* future, void* data) {
  CassSession* session = (CassSession*)data;
  CassError code = cass_future_error_code(future);

  if (code != CASS_OK) {
    print_error(future);
    signal_exit(NULL);
    return;
  }

  execute_query(session,
                "CREATE KEYSPACE examples WITH replication = { "
                "'class': 'SimpleStrategy', 'replication_factor': '3' };",
                on_create_keyspace);
}
示例#7
0
void on_insert(CassFuture* future, void* data) {
  CassError code = cass_future_error_code(future);
  if (code != CASS_OK) {
    print_error(future);
    signal_exit((CassSession*)data);
  } else {
    const char* select_query = "SELECT * FROM callbacks";
    CassStatement* statement
        = cass_statement_new(select_query, 0);
    CassFuture* select_future
        = cass_session_execute((CassSession*)data, statement);

    cass_future_set_callback(select_future, on_select, data);

    cass_statement_free(statement);
    cass_future_free(select_future);
  }
}
void 
list_read_data_callback(
    void *                                      callback_arg,
    globus_ftp_control_handle_t *               handle,
    globus_object_t *                           error,
    globus_byte_t *                             buffer,
    globus_size_t                               length,
    globus_off_t                                offset,
    globus_bool_t                               eof)
{
    get_put_info_t *                            get_put_info;

    get_put_info = (get_put_info_t *) callback_arg;
    if(error != GLOBUS_NULL)
    {
        verbose_printf(1, "unable to list files\n");
	monitor.rc = GLOBUS_FALSE;
	signal_exit();
    }
							 
    buffer[length] = '\0';
    verbose_printf(3, "%s", buffer);

    if (!eof) 
    {
        globus_ftp_control_data_read(
            handle,
            get_put_info->buffer,
            get_put_info->buffer_size,
            list_read_data_callback,
            (void *) get_put_info);
    } 
    else 
    {
        verbose_printf(2, "we have eof\n");
        globus_mutex_lock(&data_monitor.mutex);
	{
	    data_monitor.done = GLOBUS_TRUE;
	    globus_cond_signal(&data_monitor.cond);
        }
	globus_mutex_unlock(&data_monitor.mutex);
    }
}
示例#9
0
void controlCHandler (int signal)
{
    printf("Ctrl-C pressed. Killing the application ...\n");

    sem_unlink(NAVD_SEM_F_PATH);
    sem_unlink(NAVD_SEM_E_PATH);
    unlink(NAVD_BUFFER_PATH);
    sem_unlink(CMD_SEM_F_PATH);
    sem_unlink(CMD_SEM_E_PATH);
    unlink(CMD_BUFFER_PATH);
    sem_unlink(VID_SEM_F_PATH);
    sem_unlink(VID_SEM_E_PATH);
    unlink(VID_BUFFER_PATH);
    exit(-1);

    gtk_main_quit ();
    signal_exit ();
    // Flush all streams before terminating
    fflush (NULL);
    usleep (200000); // Wait 200 msec to be sure that flush occured
    printf ("\nAll files were flushed\n");
    exit (0);
}
示例#10
0
void controlCHandler (int signal)
{
	static int callCounter=0;

	callCounter++;

	/* In case GTK in unresponsive, force killing the application */
	if(callCounter>3){
		printf("Ctrl-C pressed several times. Killing the application ...\n");
		exit(-1);
	}

#if CONTROL_C_HANDLER_USES_ARDRONE_TOOL_EXIT
    gtk_main_quit ();
    signal_exit ();
#else
    // Flush all streams before terminating
    fflush (NULL);
    usleep (200000); // Wait 200 msec to be sure that flush occured
    printf ("\nAll files were flushed\n");
    exit (0);
#endif
}
示例#11
0
文件: main.c 项目: J65mesW/RedPitaya
/******************************************************************************
 * non-static function definitions
 ******************************************************************************/
int main(int argc, char **argv)
{
	int retval;
	struct handles handles = {
			.sock = -1,
			.sock2 = -1,
			.server_sock = -1,
			.file = NULL,
			.file2 = NULL,
	};
	struct scope_parameter param;

	if(0 != handle_options(argc,argv, &g_options))
	{
		usage(argv[0]);
		return 1;
	}

	signal_init();

	if (scope_init(&param, &g_options)) {
		retval = 2;
		goto cleanup;
	}

	if (g_options.mode == client || g_options.mode == server) {
		if (connection_init(&g_options, &handles)) {
			retval = 3;
			goto cleanup_scope;
		}
	} else if (g_options.mode == file) {
		if (file_open(&g_options, &handles)) {
			retval = 4;
			goto cleanup_scope;
		}
	}

	retval = 0;
	while (!transfer_interrupted()) {
		if (g_options.mode == client || g_options.mode == server) {
			if (connection_start(&g_options, &handles) < 0) {
				fprintf(stderr, "%s: problem opening connection.\n", __func__);
				continue;
			}
		}

		retval = transfer_data(&param, &g_options, &handles);
		if (retval && !transfer_interrupted())
			fprintf(stderr, "%s: problem transferring data.\n", __func__);

		if (g_options.mode == client || g_options.mode == server)
			connection_stop(&handles);

		if (g_options.mode == file)
			break;
	}

	connection_cleanup(&handles);
	file_close(&handles);

cleanup_scope:
	scope_cleanup(&param, &g_options);
cleanup:
	signal_exit();

	return retval;
}
示例#12
0
int main(int argc, char **argv) {
	int exit_code = EXIT_FAILURE;
	int i;
	bool help = false;
	bool version = false;
	bool check_config = false;
	bool daemon = false;
	bool debug = false;
	bool libusb_debug = false;
	int pid_fd = -1;
#ifdef BRICKD_WITH_LIBUDEV
	bool initialized_udev = false;
#endif

	for (i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "--help") == 0) {
			help = true;
		} else if (strcmp(argv[i], "--version") == 0) {
			version = true;
		} else if (strcmp(argv[i], "--check-config") == 0) {
			check_config = true;
		} else if (strcmp(argv[i], "--daemon") == 0) {
			daemon = true;
		} else if (strcmp(argv[i], "--debug") == 0) {
			debug = true;
		} else if (strcmp(argv[i], "--libusb-debug") == 0) {
			libusb_debug = true;
		} else {
			fprintf(stderr, "Unknown option '%s'\n\n", argv[i]);
			print_usage();

			return EXIT_FAILURE;
		}
	}

	if (help) {
		print_usage();

		return EXIT_SUCCESS;
	}

	if (version) {
		printf("%s\n", VERSION_STRING);

		return EXIT_SUCCESS;
	}

	if (prepare_paths() < 0) {
		return EXIT_FAILURE;
	}

	if (check_config) {
		return config_check(_config_filename) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
	}

	config_init(_config_filename);

	log_init();

	if (daemon) {
		pid_fd = daemon_start(_log_filename, _pid_filename, true);
	} else {
		pid_fd = pid_file_acquire(_pid_filename, getpid());

		if (pid_fd == PID_FILE_ALREADY_ACQUIRED) {
			fprintf(stderr, "Already running according to '%s'\n", _pid_filename);
		}
	}

	if (pid_fd < 0) {
		goto error_log;
	}

	log_set_debug_override(debug);

	log_set_level(LOG_CATEGORY_EVENT, config_get_option("log_level.event")->value.log_level);
	log_set_level(LOG_CATEGORY_USB, config_get_option("log_level.usb")->value.log_level);
	log_set_level(LOG_CATEGORY_NETWORK, config_get_option("log_level.network")->value.log_level);
	log_set_level(LOG_CATEGORY_HOTPLUG, config_get_option("log_level.hotplug")->value.log_level);
	log_set_level(LOG_CATEGORY_HARDWARE, config_get_option("log_level.hardware")->value.log_level);
	log_set_level(LOG_CATEGORY_WEBSOCKET, config_get_option("log_level.websocket")->value.log_level);
#ifdef BRICKD_WITH_RED_BRICK
	log_set_level(LOG_CATEGORY_RED_BRICK, config_get_option("log_level.red_brick")->value.log_level);
	log_set_level(LOG_CATEGORY_SPI, config_get_option("log_level.spi")->value.log_level);
	log_set_level(LOG_CATEGORY_RS485, config_get_option("log_level.rs485")->value.log_level);
#endif
	log_set_level(LOG_CATEGORY_OTHER, config_get_option("log_level.other")->value.log_level);

	if (config_has_error()) {
		log_error("Error(s) in config file '%s', run with --check-config option for details",
		          _config_filename);

		goto error_config;
	}

	if (daemon) {
		log_info("Brick Daemon %s started (daemonized)", VERSION_STRING);
	} else {
		log_info("Brick Daemon %s started", VERSION_STRING);
	}

	if (config_has_warning()) {
		log_error("Warning(s) in config file '%s', run with --check-config option for details",
		          _config_filename);
	}

	if (event_init() < 0) {
		goto error_event;
	}

	if (signal_init(handle_sigusr1) < 0) {
		goto error_signal;
	}

	if (hardware_init() < 0) {
		goto error_hardware;
	}

	if (usb_init(libusb_debug) < 0) {
		goto error_usb;
	}

#ifdef BRICKD_WITH_LIBUDEV
	if (!usb_has_hotplug()) {
		if (udev_init() < 0) {
			goto error_udev;
		}

		initialized_udev = true;
	}
#endif

	if (network_init() < 0) {
		goto error_network;
	}

#ifdef BRICKD_WITH_RED_BRICK
	if (gpio_init() < 0) {
		goto error_gpio;
	}

	if (red_usb_gadget_init() < 0) {
		goto error_red_usb_gadget;
	}

	if (redapid_init() < 0) {
		goto error_redapid;
	}

	if (red_stack_init() < 0) {
		goto error_red_stack;
	}

	if (rs485_extension_init() < 0) {
		goto error_rs485_extension;
	}
#endif

	if (event_run(network_cleanup_clients_and_zombies) < 0) {
		goto error_run;
	}

	exit_code = EXIT_SUCCESS;

error_run:
#ifdef BRICKD_WITH_RED_BRICK
	rs485_extension_exit();

error_rs485_extension:
	red_stack_exit();
    
error_red_stack:
	redapid_exit();

error_redapid:
	red_usb_gadget_exit();

error_red_usb_gadget:
	//gpio_exit();

error_gpio:
#endif
	network_exit();

error_network:
#ifdef BRICKD_WITH_LIBUDEV
	if (initialized_udev) {
		udev_exit();
	}

error_udev:
#endif
	usb_exit();

error_usb:
	hardware_exit();

error_hardware:
	signal_exit();

error_signal:
	event_exit();

error_event:
	log_info("Brick Daemon %s stopped", VERSION_STRING);

error_config:
error_log:
	log_exit();

	if (pid_fd >= 0) {
		pid_file_release(_pid_filename, pid_fd);
	}

	config_exit();

	return exit_code;
}
void
simple_dir_response_callback(
    void *                                      callback_arg,
    globus_ftp_control_handle_t *               handle,
    globus_object_t *                           error,
    globus_ftp_control_response_t *             ftp_response)
{
    get_put_info_t *                            get_put_info;
    globus_result_t                             result; 

    if (ftp_response->code == 200) 
    {
       verbose_printf(2, "%s\n", ftp_response->response_buffer);

       get_put_info = (get_put_info_t *) globus_malloc(sizeof(get_put_info_t));
       get_put_info->buffer_size = BUFFER_SIZE;
       get_put_info->buffer = globus_malloc(BUFFER_SIZE);

       result = globus_ftp_control_send_command(
           handle,
           "LIST\r\n",
           simple_dir_response_callback,
           (void *)get_put_info);
       if (result != GLOBUS_SUCCESS)
       {
           verbose_printf(1, "LIST failed\n");
	   monitor.rc = GLOBUS_FALSE;
           signal_exit();
       }

       result = globus_ftp_control_data_connect_read(
           handle, GLOBUS_NULL, GLOBUS_NULL);
       if (result != GLOBUS_SUCCESS)
       {
          verbose_printf(1, "ls failed\n");
	  monitor.rc = GLOBUS_FALSE;
	  signal_exit();
       }
    } 
    else if (ftp_response->code == 150) 
    {
        verbose_printf(2, "%s\n", ftp_response->response_buffer);

        get_put_info = (get_put_info_t *)callback_arg;

        data_monitor.done = GLOBUS_FALSE;
        globus_ftp_control_data_read(
            handle,
	    get_put_info->buffer,
	    get_put_info->buffer_size,
	    list_read_data_callback, 
	    (void *) get_put_info);
    } 
    else if (ftp_response->code == 226)
    { 
        globus_mutex_lock(&data_monitor.mutex);
	{
	    while(!data_monitor.done)
	    {
	        globus_cond_wait(&data_monitor.cond, &data_monitor.mutex);
            }
        }
	globus_mutex_unlock(&data_monitor.mutex);

        verbose_printf(2, "%s\n", ftp_response->response_buffer);

        monitor.rc = GLOBUS_TRUE;
        signal_exit();
    } 
    else 
    {
        verbose_printf(1, "Error: %s\n", ftp_response->response_buffer);
	monitor.rc = GLOBUS_FALSE;
	signal_exit();
    }
}
示例#14
0
int main(int argc, char **argv) {
	int exit_code = EXIT_FAILURE;
	int i;
	bool help = false;
	bool version = false;
	bool check_config = false;
	bool daemon = false;
	const char *debug_filter = NULL;
	bool libusb_debug = false;
	int pid_fd = -1;

	for (i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "--help") == 0) {
			help = true;
		} else if (strcmp(argv[i], "--version") == 0) {
			version = true;
		} else if (strcmp(argv[i], "--check-config") == 0) {
			check_config = true;
		} else if (strcmp(argv[i], "--daemon") == 0) {
			daemon = true;
		} else if (strcmp(argv[i], "--debug") == 0) {
			if (i + 1 < argc && strncmp(argv[i + 1], "--", 2) != 0) {
				debug_filter = argv[++i];
			} else {
				debug_filter = "";
			}
		} else if (strcmp(argv[i], "--libusb-debug") == 0) {
			libusb_debug = true;
		} else {
			fprintf(stderr, "Unknown option '%s'\n\n", argv[i]);
			print_usage();

			return EXIT_FAILURE;
		}
	}

	if (help) {
		print_usage();

		return EXIT_SUCCESS;
	}

	if (version) {
		printf("%s\n", VERSION_STRING);

		return EXIT_SUCCESS;
	}

	if (check_config) {
		return config_check(CONFIG_FILENAME) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
	}

	config_init(CONFIG_FILENAME);

	if (config_has_error()) {
		fprintf(stderr, "Error(s) occurred while reading config file '%s'\n",
		        CONFIG_FILENAME);

		goto error_config;
	}

	log_init();

	if (daemon) {
		pid_fd = daemon_start(LOG_FILENAME, PID_FILENAME, false);
	} else {
		pid_fd = pid_file_acquire(PID_FILENAME, getpid());

		if (pid_fd == PID_FILE_ALREADY_ACQUIRED) {
			fprintf(stderr, "Already running according to '%s'\n", PID_FILENAME);
		}
	}

	if (pid_fd < 0) {
		goto error_pid_file;
	}

	log_info("Brick Daemon %s started (pid: %u, daemonized: %d)",
	         VERSION_STRING, getpid(), daemon ? 1 : 0);

	if (debug_filter != NULL) {
		log_enable_debug_override(debug_filter);
	}

	if (config_has_warning()) {
		log_warn("Warning(s) in config file '%s', run with --check-config option for details",
		         CONFIG_FILENAME);
	}

	if (event_init() < 0) {
		goto error_event;
	}

	if (signal_init(NULL, handle_sigusr1) < 0) {
		goto error_signal;
	}

	if (hardware_init() < 0) {
		goto error_hardware;
	}

	if (usb_init(libusb_debug) < 0) {
		goto error_usb;
	}

	if (iokit_init() < 0) {
		goto error_iokit;
	}

	if (network_init() < 0) {
		goto error_network;
	}

	if (event_run(network_cleanup_clients_and_zombies) < 0) {
		goto error_run;
	}

	exit_code = EXIT_SUCCESS;

error_run:
	network_exit();

error_network:
	iokit_exit();

error_iokit:
	usb_exit();

error_usb:
	hardware_exit();

error_hardware:
	signal_exit();

error_signal:
	event_exit();

error_event:
	log_info("Brick Daemon %s stopped", VERSION_STRING);

error_pid_file:
	if (pid_fd >= 0) {
		pid_file_release(PID_FILENAME, pid_fd);
	}

	log_exit();

error_config:
	config_exit();

	return exit_code;
}
void err_exit() {
  signal_exit (-1);
}
示例#16
0
int main(int argc, char **argv) {
	int exit_code = EXIT_FAILURE;
	int i;
	bool help = false;
	bool version = false;
	bool check_config = false;
	bool daemon = false;
	const char *debug_filter = NULL;
	int pid_fd = -1;

	for (i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "--help") == 0) {
			help = true;
		} else if (strcmp(argv[i], "--version") == 0) {
			version = true;
		} else if (strcmp(argv[i], "--check-config") == 0) {
			check_config = true;
		} else if (strcmp(argv[i], "--daemon") == 0) {
			daemon = true;
		} else if (strcmp(argv[i], "--debug") == 0) {
			if (i + 1 < argc && strncmp(argv[i + 1], "--", 2) != 0) {
				debug_filter = argv[++i];
			} else {
				debug_filter = "";
			}
		} else {
			fprintf(stderr, "Unknown option '%s'\n\n", argv[i]);
			print_usage();

			return EXIT_FAILURE;
		}
	}

	if (help) {
		print_usage();

		return EXIT_SUCCESS;
	}

	if (version) {
		printf("%s\n", VERSION_STRING);

		return EXIT_SUCCESS;
	}

	read_image_version();

	_x11_enabled = access("/etc/tf_x11_enabled", F_OK) == 0;

	if (prepare_paths() < 0) {
		return EXIT_FAILURE;
	}

	if (check_config) {
		return config_check(_config_filename) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
	}

	config_init(_config_filename);

	if (config_has_error()) {
		fprintf(stderr, "Error(s) occurred while reading config file '%s'",
		        _config_filename);

		goto error_config;
	}

	log_init();

	if (daemon) {
		pid_fd = daemon_start(_log_filename, _pid_filename, 1);
	} else {
		pid_fd = pid_file_acquire(_pid_filename, getpid());

		if (pid_fd == PID_FILE_ALREADY_ACQUIRED) {
			fprintf(stderr, "Already running according to '%s'\n", _pid_filename);
		}
	}

	if (pid_fd < 0) {
		goto error_pid_file;
	}

	if (daemon && _x11_enabled) {
		log_info("RED Brick API Daemon %s started (daemonized, X11 enabled) on %s image",
		         VERSION_STRING, _image_version);
	} else if (daemon) {
		log_info("RED Brick API Daemon %s started (daemonized) on %s image",
		         VERSION_STRING, _image_version);
	} else if (_x11_enabled) {
		log_info("RED Brick API Daemon %s started (X11 enabled) on %s image",
		         VERSION_STRING, _image_version);
	} else {
		log_info("RED Brick API Daemon %s started on %s image",
		         VERSION_STRING, _image_version);
	}

	if (debug_filter != NULL) {
		log_enable_debug_override(debug_filter);
	}

	if (config_has_warning()) {
		log_warn("Warning(s) in config file '%s', run with --check-config option for details",
		         _config_filename);
	}

	if (event_init() < 0) {
		goto error_event;
	}

	if (signal_init(handle_sighup, NULL) < 0) {
		goto error_signal;
	}

	if (process_monitor_init() < 0) {
		goto error_process_monitor;
	}

	if (cron_init() < 0) {
		goto error_cron;
	}

	if (inventory_init() < 0) {
		goto error_inventory;
	}

	if (api_init() < 0) {
		goto error_api;
	}

	if (network_init(_brickd_socket_filename, _cron_socket_filename) < 0) {
		goto error_network;
	}

	if (inventory_load_programs() < 0) {
		goto error_load_programs;
	}

	if (event_run(network_cleanup_brickd_and_socats) < 0) {
		goto error_run;
	}

	exit_code = EXIT_SUCCESS;

error_run:
	inventory_unload_programs();

error_load_programs:
	network_exit();

error_network:
	api_exit();

error_api:
	inventory_exit();

error_inventory:
	cron_exit();

error_cron:
	process_monitor_exit();

error_process_monitor:
	signal_exit();

error_signal:
	event_exit();

error_event:
	log_info("RED Brick API Daemon %s stopped", VERSION_STRING);

error_pid_file:
	if (pid_fd >= 0) {
		pid_file_release(_pid_filename, pid_fd);
	}

	log_exit();

error_config:
	config_exit();

	return exit_code;
}
示例#17
0
int main(int argc, char **argv) {
	int exit_code = EXIT_FAILURE;
	int i;
	bool help = false;
	bool version = false;
	bool check_config = false;
	bool daemon = false;
	const char *debug_filter = NULL;
	int pid_fd = -1;
#ifdef BRICKD_WITH_LIBUDEV
	bool initialized_udev = false;
#endif

	for (i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "--help") == 0) {
			help = true;
		} else if (strcmp(argv[i], "--version") == 0) {
			version = true;
		} else if (strcmp(argv[i], "--check-config") == 0) {
			check_config = true;
		} else if (strcmp(argv[i], "--daemon") == 0) {
			daemon = true;
		} else if (strcmp(argv[i], "--debug") == 0) {
			if (i + 1 < argc && strncmp(argv[i + 1], "--", 2) != 0) {
				debug_filter = argv[++i];
			} else {
				debug_filter = "";
			}
		} else {
			fprintf(stderr, "Unknown option '%s'\n\n", argv[i]);
			print_usage();

			return EXIT_FAILURE;
		}
	}

	if (help) {
		print_usage();

		return EXIT_SUCCESS;
	}

	if (version) {
		printf("%s\n", VERSION_STRING);

		return EXIT_SUCCESS;
	}

	if (prepare_paths() < 0) {
		return EXIT_FAILURE;
	}

	if (check_config) {
		return config_check(_config_filename) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
	}

	config_init(_config_filename);

	if (config_has_error()) {
		fprintf(stderr, "Error(s) occurred while reading config file '%s'\n",
		        _config_filename);

		goto error_config;
	}

	log_init();

	if (daemon) {
		pid_fd = daemon_start(_log_filename, &_log_file, _pid_filename, true);
	} else {
		pid_fd = pid_file_acquire(_pid_filename, getpid());

		if (pid_fd == PID_FILE_ALREADY_ACQUIRED) {
			fprintf(stderr, "Already running according to '%s'\n", _pid_filename);
		}
	}

	if (pid_fd < 0) {
		goto error_pid_file;
	}

	log_info("Brick Daemon %s started (pid: %u, daemonized: %d)",
	         VERSION_STRING, getpid(), daemon ? 1 : 0);

	if (debug_filter != NULL) {
		log_enable_debug_override(debug_filter);
	}

	if (config_has_warning()) {
		log_warn("Warning(s) in config file '%s', run with --check-config option for details",
		         _config_filename);
	}

	if (event_init() < 0) {
		goto error_event;
	}

	if (signal_init(handle_sighup, handle_sigusr1) < 0) {
		goto error_signal;
	}

	if (hardware_init() < 0) {
		goto error_hardware;
	}

	if (usb_init() < 0) {
		goto error_usb;
	}

#ifdef BRICKD_WITH_LIBUDEV
	if (!usb_has_hotplug()) {
		if (udev_init() < 0) {
			goto error_udev;
		}

		initialized_udev = true;
	}
#endif

	if (network_init() < 0) {
		goto error_network;
	}

	if (mesh_init() < 0) {
		goto error_mesh;
	}

#ifdef BRICKD_WITH_RED_BRICK
	if (gpio_init() < 0) {
		goto error_gpio;
	}

	if (redapid_init() < 0) {
		goto error_redapid;
	}

	if (red_stack_init() < 0) {
		goto error_red_stack;
	}

	if (red_extension_init() < 0) {
		goto error_red_extension;
	}

	if (red_usb_gadget_init() < 0) {
		goto error_red_usb_gadget;
	}

	red_led_set_trigger(RED_LED_GREEN, config_get_option_value("led_trigger.green")->symbol);
	red_led_set_trigger(RED_LED_RED, config_get_option_value("led_trigger.red")->symbol);
#endif

	if (event_run(network_cleanup_clients_and_zombies) < 0) {
		goto error_run;
	}

#ifdef BRICKD_WITH_RED_BRICK
	hardware_announce_disconnect();
	network_announce_red_brick_disconnect();
	red_usb_gadget_announce_red_brick_disconnect();
#endif

	exit_code = EXIT_SUCCESS;

error_run:
#ifdef BRICKD_WITH_RED_BRICK
	red_usb_gadget_exit();

error_red_usb_gadget:
	red_extension_exit();

error_red_extension:
	red_stack_exit();

error_red_stack:
	redapid_exit();

error_redapid:
	//gpio_exit();

error_gpio:
#endif
	network_exit();

error_mesh:
	mesh_exit();

error_network:
#ifdef BRICKD_WITH_LIBUDEV
	if (initialized_udev) {
		udev_exit();
	}

error_udev:
#endif
	usb_exit();

error_usb:
	hardware_exit();

error_hardware:
	signal_exit();

error_signal:
	event_exit();

error_event:
	log_info("Brick Daemon %s stopped", VERSION_STRING);

error_pid_file:
	if (pid_fd >= 0) {
		pid_file_release(_pid_filename, pid_fd);
	}

	log_exit();

error_config:
	config_exit();

	return exit_code;
}
示例#18
0
int main (int argc, char **argv)
{
  char *user_line = NULL, *qp_reply = NULL;
  size_t qp_reply_len = 0, user_len = 0;
  int ret = 0;
  /* reading to the from Quickplot */
  FILE *file_from = NULL;
  char path_to[FIFO_PATH_LEN], path_from[FIFO_PATH_LEN];
  *path_to = '\0';
  *path_from = '\0';

  if(argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")))
    usage();

  if(argc == 2 && argv[1][0] > '0' && argv[1][0] < '9')
  {
    char *end;
    pid = strtoul(argv[1], &end, 10);
    if(*end != '\0')
    {
      printf("Cannot parse PID from \"%s\"\n\n", argv[1]);
      usage();
    }
  }

  if(pid == -1)
  {
    char *qp_path;
    size_t len;
    len = strlen(argv[0]);
    /* remove the _shell part of stuff/path_to/quickplot_shell */
    if(len >= 15)
    {
      qp_path = qp_strdup(argv[0]);
      qp_path[len-6] = '\0';
    }
    else
      qp_path = qp_strdup("quickplot");

    signal(SIGUSR1, usr1_catcher);

    errno = 0;
    pid = fork();
    if(pid == -1)
    {
      QP_EERROR("failed to fork()\n");
      return 1;
    }
    if(pid != 0)
    {
      // parent runs quickplot
      char **e_argv;
      int i;
      char last_arg[64];
      e_argv = qp_malloc((argc+2)*sizeof(*e_argv));
      e_argv[0] = qp_strdup("quickplot");
      for(i=1;i<argc;++i)
        e_argv[i] = argv[i];
      snprintf(last_arg, 64, "--signal=%d", pid);
      e_argv[i++] = last_arg;
      e_argv[i] = NULL;
      execv(qp_path, e_argv);
      QP_EERROR("failed to execute %s\n", qp_path);
      // we failed, kill my child.
      kill(pid, SIGINT);
      return 1; // failed
    }
    else
    {
      pid = getppid();
      /* wait for sig SIGCONT */
      DEBUG("pid=%d waiting for signal\n", getpid());
      while(!got_usr1)
        usleep(100000);
      DEBUG("pid=%d got signal\n", getpid());
    }
  }

  errno = 0;
  if(kill(pid, SIGCONT))
  {
    QP_EERROR("Failed to signal pid %d\n", pid);
    return 1;
  }

  errno = 0;
  if(mkfifo(set_to_qp_fifo_path(path_to, pid, getpid()),
        S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))
  {
    QP_EERROR("Failed to create fifo %s\n", path_to);
    *path_to = '\0';
    ret = 1;
    goto cleanup;
  }
  errno = 0;
  if(mkfifo(set_from_qp_fifo_path(path_from, pid, getpid()),
        S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))
  {
    QP_EERROR("Failed to create fifo %s\n", path_from);
    *path_from = '\0';
    ret = 1;
    goto cleanup;
  }
  /* Since the FIFO block on fopen(,"r") we will signal
   * before we call fopen(,"r").
   *
   * Looks like fopen(,"w") blocks too. */
  errno = 0;
  if(kill(pid, SIGUSR1))
  {
    QP_EERROR("Failed to signal pid %d\n", pid);
    return 1;
  }

  errno = 0;
  if(!(file_to = fopen(path_to, "w")))
  {
    QP_EERROR("fopen(\"%s\",\"a\") failed\n", path_to);
    ret = 1;
    goto cleanup_with_signal;
  }
  errno = 0;
  if(!(file_from = fopen(path_from, "r")))
  {
    QP_EERROR("fopen(\"%s\",\"r\") failed\n", path_from);
    ret = 1;
    goto cleanup_with_signal;
  }
  setlinebuf(file_from);

  prompt = allocate_prompt();

#ifdef QP_DEBUG
  signal(SIGSEGV, debug_sighandler);
  signal(SIGABRT, debug_sighandler);
#endif

  signal(SIGTERM, term_sighandler);
  signal(SIGQUIT, term_sighandler);
  signal(SIGINT, term_sighandler);

stdin_isatty = isatty(fileno(stdin));
qp_shell_initialize(1);

#ifdef HAVE_LIBREADLINE
  if(stdin_isatty)
  {
    use_readline = 1;
    printf("Using readline version: %d.%d\n",
        RL_VERSION_MAJOR, RL_VERSION_MINOR);
  }
  else
  {
#else
    printf("Using getline()\n");
#endif
#ifdef HAVE_LIBREADLINE
  }
#endif

  /* Exercise the pipe so it does not block the Quickplot
   * service on fopen(,"r"). */
  fprintf(file_to, "start\n");
  fflush(file_to);

  if(read_and_spew_until_end(&qp_reply, &qp_reply_len, file_from, pid))
    goto cleanup_with_signal;

  /* We can hide the FIFO files now that both parties are connected.
   * The OS will keep the FIFO files in existence so long as one of
   * the two processes have them open. */
  unlink(path_to);
  *path_to = '\0';
  unlink(path_from);
  *path_from = '\0';

  while((Getline(&user_line, &user_len)))
  {
    char **argv;
    int argc;
    size_t len;
    char *history_mem = NULL;
    len = strlen(user_line) + 1;
    argv = get_args(user_line, &argc);

    if(argc > 0)
    {
      if(!strcmp("exit", *argv)) // exit
        break;
      if(!strcmp("quit", *argv)) // quit
      {
        fprintf(file_to, "quit\n");
        fflush(file_to);
        break;
      }

      if(process_client_side_commands(&argc, &argv,
            stdin, stdout, len, &history_mem
#ifdef HAVE_LIBREADLINE
          , 0, &use_readline
#endif
          ))
      {
        if(!strcmp("input", *argv) && argc > 1)
        {
          stdin_isatty = isatty(fileno(stdin));
        }
      }
      else // command to server
      {
        int i;
#ifdef QP_DEBUG
        if(SPEW_LEVEL() <= 1)
        {
          printf("Read user line: \"%s\"", argv[0]);
          for(i=1; i<argc; ++i)
            printf(" %s", argv[i]);
          printf("\n");
        }
#endif
        fprintf(file_to, "%s", argv[0]);
        for(i=1; i<argc; ++i)
          fprintf(file_to, " %s", argv[i]);
        fprintf(file_to,"\n");
        fflush(file_to);

        // read and print reply
        if(read_and_spew_until_end(&qp_reply, &qp_reply_len, file_from, pid))
          goto cleanup_with_signal;
      }
    }
    if(history_mem)
      free(history_mem);
    free(argv);
  }

#ifdef HAVE_READLINE_HISTORY
  Save_history();
#endif

cleanup_with_signal:

  signal_exit();

cleanup:

  if(*path_to)
    unlink(path_to);
  if(*path_from)
    unlink(path_from);

  printf("exiting\n");
  return ret;
}