static void
setup_signals (void)
{
    signal (SIGPIPE, SIG_IGN);
    g_unix_signal_add (SIGINT, quit_handler, NULL);
    g_unix_signal_add (SIGTERM, quit_handler, NULL);
}
gint
main (gint                argc,
      const gchar * const argv[])
{
  EmerDaemon *daemon = make_daemon (argc, argv);
  if (daemon == NULL)
    return EXIT_FAILURE;

  GMainLoop *main_loop = g_main_loop_new (NULL, TRUE);

  // Shut down on any of these signals.
  g_unix_signal_add (SIGHUP, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGINT, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGTERM, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGUSR1, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGUSR2, (GSourceFunc) quit_main_loop, main_loop);

  guint name_id = g_bus_own_name (G_BUS_TYPE_SYSTEM, "com.endlessm.Metrics",
                                  G_BUS_NAME_OWNER_FLAGS_NONE,
                                  on_bus_acquired,
                                  NULL /* name_acquired_callback */,
                                  on_name_lost,
                                  daemon, NULL /* user data free func */);

  g_main_loop_run (main_loop);

  g_object_unref (daemon);
  g_bus_unown_name (name_id);
  g_main_loop_unref (main_loop);

  return EXIT_SUCCESS;
}
Example #3
0
static void
create_manager (void)
{
        GsmStore *client_store;

        client_store = gsm_store_new ();
        manager = gsm_manager_new (client_store, failsafe);
        g_object_unref (client_store);

        g_unix_signal_add (SIGTERM, term_or_int_signal_cb, manager);
        g_unix_signal_add (SIGINT, term_or_int_signal_cb, manager);
        g_unix_signal_add (SIGUSR1, sigusr1_cb, manager);
        g_unix_signal_add (SIGUSR2, sigusr2_cb, manager);

        if (IS_STRING_EMPTY (session_name)) {
                session_name = _gsm_manager_get_default_session (manager);
        }

        if (!gsm_session_fill (manager, session_name)) {
                gsm_fail_whale_dialog_we_failed (FALSE, TRUE, NULL);
        }

        _gsm_manager_set_renderer (manager, gl_renderer);
        gsm_manager_start (manager);
}
Example #4
0
static void
initialize_signal_handler (void)
{
#ifndef G_OS_WIN32
	g_unix_signal_add (SIGTERM, signal_handler, GINT_TO_POINTER (SIGTERM));
	g_unix_signal_add (SIGINT, signal_handler, GINT_TO_POINTER (SIGINT));
#endif /* G_OS_WIN32 */
}
Example #5
0
int main (int argc, char *argv[])
{
    SourceAppData data;
    data.port = 7236;

    GOptionEntry main_entries[] =
    {
        { "rtsp_port", 0, 0, G_OPTION_ARG_INT, &(data.port), "Specify optional RTSP port number, 7236 by default", "rtsp_port"},
        { NULL }
    };

    GOptionContext* context = g_option_context_new ("- WFD desktop source demo application\n");
    g_option_context_add_main_entries (context, main_entries, NULL);
    g_option_context_add_group (context, gst_init_get_option_group ());

    GError* error = NULL;
    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        g_print ("option parsing failed: %s\n", error->message);
        g_option_context_free(context);
        exit (1);
    }
    g_option_context_free(context);

    GMainLoop *main_loop =  g_main_loop_new(NULL, TRUE);
    g_unix_signal_add(SIGINT, _sig_handler, main_loop);
    g_unix_signal_add(SIGTERM, _sig_handler, main_loop);

    GIOChannel* io_channel = g_io_channel_unix_new (STDIN_FILENO);
    g_io_add_watch(io_channel, G_IO_IN, _user_input_handler, &data);
    g_io_channel_unref(io_channel);

    // Create a information element for a simple WFD Source
    // FIXME: is this correct? maybe we're supposed to actively scan for
    // WFD sinks instead
    P2P::InformationElement ie;
    auto sub_element = P2P::new_subelement(P2P::DEVICE_INFORMATION);
    auto dev_info = (P2P::DeviceInformationSubelement*)sub_element;
    dev_info->session_management_control_port =  htons(data.port);
    dev_info->maximum_throughput = htons(50);
    dev_info->field1.device_type = P2P::SOURCE;
    dev_info->field1.session_availability = true;
    ie.add_subelement (sub_element);

    std::cout << "Registering Wifi Source on port with IE " << ie.to_string() <<  std::endl;

    // register the P2P service with connman
    auto array = ie.serialize ();
    data.connman.reset(new ConnmanClient (array));

    if (create_source(&data))
        g_main_loop_run (main_loop);

    g_main_loop_unref (main_loop);

    return 0;
}
Example #6
0
/* The main() function. */
int main(int argc, char **argv)
{
        struct sigaction sa;
        GIOChannel *channel;

        setlocale(LC_CTYPE, "");

        /* Cleanup and signal handling */
        atexit(cleanup);

        g_unix_signal_add(SIGINT, signal_handler, NULL);
        g_unix_signal_add(SIGTERM, signal_handler, NULL);


        sa.sa_handler = signal_fatal;
        sa.sa_flags = SA_RESETHAND;
        sigemptyset(&sa.sa_mask);
        sigaction(SIGABRT, &sa, 0);
        sigaction(SIGBUS, &sa, 0);
        sigaction(SIGFPE, &sa, 0);
        sigaction(SIGILL, &sa, 0);
        sigaction(SIGSEGV, &sa, 0);

        /* App core */
        kixterm.app = kt_app_new();
        /* Preferences */
        kixterm.prefs = kt_prefs_new();
        /* Font */
        kixterm.font = kt_font_new(kixterm.app, kixterm.prefs);
        /* Color */
        kixterm.color = kt_color_new(kixterm.app, kixterm.prefs);
        /* Main window */
        kixterm.win = kt_window_new(kixterm.app,
                                    kixterm.prefs,
                                    kixterm.font,
                                    kixterm.color);

        /* Watch the X file descriptor for events */
        channel = g_io_channel_unix_new(kt_app_get_xfd(kixterm.app));
        g_io_add_watch(channel, G_IO_IN, kt_xcb_io_cb, NULL);
        g_io_channel_unref(channel);

        /* Main context */
        g_main_context_set_poll_func(g_main_context_default(), &kt_poll);

        /* main event loop */
        loop = g_main_loop_new(NULL, FALSE);

        g_main_loop_run(loop);

        /* Cleanup */
        g_main_loop_unref(loop);
        loop = NULL;

        exit(EXIT_SUCCESS);
}
Example #7
0
static void
session_ready_cb (GfSession *session,
                  gpointer   user_data)
{
  g_unix_signal_add (SIGTERM, on_term_signal, NULL);
  g_unix_signal_add (SIGINT, on_int_signal, NULL);

  application = gf_application_new ();
  gf_session_register (session);
}
Example #8
0
static void
_install_sighandlers (TlmLauncher *l)
{
    if (signal (SIGINT, SIG_IGN) == SIG_ERR)
        WARN ("failed to ignore SIGINT: %s", strerror(errno));

    l->sig_source_id[0] = g_unix_signal_add (SIGTERM, _handle_quit_signal, l);
    l->sig_source_id[1] = g_unix_signal_add (SIGHUP, _handle_quit_signal, l);

    if (prctl(PR_SET_PDEATHSIG, SIGHUP))
        WARN ("failed to set parent death signal");
}
int
sol_mainloop_impl_init(void)
{
    loop = g_main_loop_new(NULL, false);
    if (!loop) {
        SOL_CRI("cannot create mainloop");
        return errno ? -errno : -ENOENT;
    }

    g_unix_signal_add(SIGINT, on_signal, loop);
    g_unix_signal_add(SIGTERM, on_signal, loop);
    return 0;
}
Example #10
0
GPid
pipe_stdio_to_hook(const gchar* envvar_name, GSourceFunc callback) {
  gchar** argv;
  gint argc;
  gchar **env = g_get_environ();
  env = g_environ_setenv(env, "NICE_REMOTE_HOSTNAME", remote_hostname, TRUE);

  gchar* cmd = g_getenv(envvar_name);
  g_debug("pipe_stdio_to_hook('%s')=%s\n", envvar_name, cmd);
  if(cmd == NULL || strlen(cmd) == 0)
    return -1;

  // parse command line to argv array
  if(!g_shell_parse_argv(cmd, &argc, &argv, NULL)) {
    g_critical("Error parsing command line '%s'", cmd);

    exit(1);
  }

  gboolean spawned;
  GPid pid;
  gint stdio[2];
  GError* error = NULL;

  g_debug("Executing '%s'\n", cmd);
  spawned = g_spawn_async_with_pipes(".", argv, env, G_SPAWN_CHILD_INHERITS_STDIN, NULL, NULL,
    &pid, NULL, NULL, NULL, &error);

  if(error != NULL) {
    g_critical("Error executing '%s': %s", cmd, error->message);
    return pid;
  }

  if(callback != NULL) {
    // no SIGCHLD, so we cannot
    // g_child_watch_add(pid, callback, NULL);

    gint interval_ms = 500;
    g_timeout_add(interval_ms, callback, (gpointer) pid);
  }

  g_unix_signal_add(SIGTERM, terminate_child_and_exit, (gpointer) pid);
  g_unix_signal_add(SIGINT, terminate_child_and_exit, (gpointer) pid);

  g_assert(spawned);

  return pid;
}
Example #11
0
int
main (int argc, char *argv[])
{
  SnraClient *client = NULL;
  int ret = 1;
  const gchar *server = NULL;

  gst_init (&argc, &argv);

  if (argc > 1) {
    /* Connect directly to the requested server, no avahi */
    server = argv[1];
  }

  avahi_set_allocator (avahi_glib_allocator ());

  g_unix_signal_add (SIGINT, sigint_handler, NULL);

  client = snra_client_new (server);
  if (client == NULL)
    goto fail;

  ml = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (ml);

  ret = 0;
fail:
  if (client)
    g_object_unref (client);
  if (ml)
    g_main_loop_unref (ml);
  return ret;
}
Example #12
0
int
main (int    argc,
      char **argv)
{
  GError *error;
  GOptionContext *opt_context = NULL;
  gint ret = 1;
  guint name_owner_id = 0;

  setlocale (LC_ALL, "");
  bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);

  opt_context = g_option_context_new ("GNOME Online Accounts daemon");
  g_option_context_add_main_entries (opt_context, opt_entries, NULL);
  error = NULL;
  if (!g_option_context_parse (opt_context, &argc, &argv, &error))
    {
      g_critical ("Error parsing options: %s", error->message);
      g_error_free (error);
      goto out;
    }

  g_message ("goa-daemon version %s starting", PACKAGE_VERSION);

  loop = g_main_loop_new (NULL, FALSE);

  if (!opt_no_sigint)
    {
      g_unix_signal_add (SIGINT, on_sigint, NULL);
    }

  name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
                                  "org.gnome.OnlineAccounts",
                                  G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT |
                                    (opt_replace ? G_BUS_NAME_OWNER_FLAGS_REPLACE : 0),
                                  on_bus_acquired,
                                  on_name_acquired,
                                  on_name_lost,
                                  NULL,
                                  NULL);

  g_debug ("Entering main event loop");

  g_main_loop_run (loop);

  ret = 0;

 out:
  g_clear_object (&the_daemon);
  if (name_owner_id != 0)
    g_bus_unown_name (name_owner_id);
  g_clear_pointer (&loop, (GDestroyNotify) g_main_loop_unref);
  g_clear_pointer (&opt_context, (GDestroyNotify) g_option_context_free);

  g_message ("goa-daemon version %s exiting", PACKAGE_VERSION);

  return ret;
}
Example #13
0
static void
korva_server_init (KorvaServer *self)
{
    self->priv = korva_server_get_instance_private (self);
    self->priv->loop = g_main_loop_new (NULL, FALSE);

    self->priv->bus_id = g_bus_own_name (G_BUS_TYPE_SESSION,
                                         "org.jensge.Korva",
                                         G_BUS_NAME_OWNER_FLAGS_NONE,
                                         korva_server_on_bus_aquired,
                                         korva_server_on_name_aquired,
                                         korva_server_on_name_lost,
                                         g_object_ref (self),
                                         g_object_unref);

    self->priv->tags = g_hash_table_new_full (g_str_hash,
                                              (GEqualFunc) g_str_equal,
                                              g_free,
                                              g_free);

#ifdef G_OS_UNIX
    g_unix_signal_add (SIGINT, korva_server_signal_handler, self);
#endif

    korva_server_reset_timeout (self);
}
Example #14
0
int
main (int argc, char ** argv)
{
    GMainLoop * loop = NULL;
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    setlocale (LC_ALL, "");
    bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);

    /* Build Mainloop */
    loop = g_main_loop_new(NULL, FALSE);

    g_unix_signal_add(SIGTERM, sigterm_handler, loop);

    /* Initialize libnotify */
    notify_init ("indicator-sound");

    g_bus_own_name(G_BUS_TYPE_SESSION,
        "com.canonical.indicator.sound",
        G_BUS_NAME_OWNER_FLAGS_NONE,
        on_bus_acquired,
        NULL, /* name acquired */
        on_name_lost,
        loop,
        NULL);

    g_main_loop_run(loop);

    g_clear_object(&service);
    g_clear_pointer(&pgloop, pa_glib_mainloop_free);

    notify_uninit();

    return 0;
}
gint
main (gint                argc,
      const gchar * const argv[])
{
  prev_time_set = emtr_util_get_current_time (CLOCK_MONOTONIC, &prev_time);
  g_datalist_init (&humanity_by_session_id);

  GDBusProxy *systemd_dbus_proxy = systemd_dbus_proxy_new ();
  GDBusProxy *login_dbus_proxy = login_dbus_proxy_new ();
  GDBusProxy *network_dbus_proxy = network_dbus_proxy_new ();
  GFileMonitor *location_file_monitor = location_file_monitor_new ();

  GMainLoop *main_loop = g_main_loop_new (NULL, TRUE);

  g_idle_add ((GSourceFunc) record_location_metric, NULL);
  g_idle_add ((GSourceFunc) record_os_version, NULL);
  g_idle_add ((GSourceFunc) increment_boot_count, NULL);
  g_idle_add ((GSourceFunc) record_live_boot, NULL);
  g_idle_add ((GSourceFunc) record_image_version, NULL);
  g_idle_add ((GSourceFunc) record_location_label, NULL);
  g_idle_add ((GSourceFunc) record_network_id, GINT_TO_POINTER (TRUE));
  g_idle_add ((GSourceFunc) record_windows_licenses, NULL);
  g_timeout_add_seconds (RECORD_UPTIME_INTERVAL_SECONDS / 2,
                         (GSourceFunc) record_uptime, NULL);

  eins_hwinfo_start ();

  g_unix_signal_add (SIGHUP, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGINT, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGTERM, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGUSR1, (GSourceFunc) quit_main_loop, main_loop);
  g_unix_signal_add (SIGUSR2, (GSourceFunc) quit_main_loop, main_loop);

  g_main_loop_run (main_loop);

  record_logout_for_all_remaining_sessions ();
  record_shutdown ();

  g_main_loop_unref (main_loop);
  g_clear_object (&systemd_dbus_proxy);
  g_clear_object (&login_dbus_proxy);
  g_clear_object (&network_dbus_proxy);
  g_clear_object (&location_file_monitor);

  return EXIT_SUCCESS;
}
Example #16
0
static void
let_me_quit (GMainLoop *loop)
{
  g_unix_signal_add (SIGINT, (GSourceFunc) g_main_loop_quit, loop);

  if (!quiet)
    g_printf ("Hit Control-C to stop logging.\n");
}
Example #17
0
int
main (int argc, char *argv[])
{
	ArgsInfo args_info = { &nm_cli, argc, argv };

	/* Set locale to use environment variables */
	setlocale (LC_ALL, "");

#ifdef GETTEXT_PACKAGE
	/* Set i18n stuff */
	bindtextdomain (GETTEXT_PACKAGE, NMCLI_LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	nm_g_type_init ();

	/* Save terminal settings */
	tcgetattr (STDIN_FILENO, &termios_orig);

	g_unix_signal_add (SIGTERM, signal_handler, GINT_TO_POINTER (SIGTERM));
	g_unix_signal_add (SIGINT, signal_handler, GINT_TO_POINTER (SIGINT));

	nmc_value_transforms_register ();

	nmc_init (&nm_cli);
	g_idle_add (start, &args_info);

	loop = g_main_loop_new (NULL, FALSE);  /* create main loop */
	g_main_loop_run (loop);                /* run main loop */

	if (nm_cli.complete) {
		/* Remove error statuses from command completion runs. */
		if (nm_cli.return_value < NMC_RESULT_COMPLETE_FILE)
			nm_cli.return_value = NMC_RESULT_SUCCESS;
	} else if (nm_cli.return_value != NMC_RESULT_SUCCESS) {
		/* Print result descripting text */
		g_printerr ("%s\n", nm_cli.return_text->str);
	}

	g_main_loop_unref (loop);
	nmc_cleanup (&nm_cli);

	return nm_cli.return_value;
}
Example #18
0
int
main (int argc, char *argv[])
{
	GError		*err;
	PiGlow		*pig;
	GMainLoop	*loop;
	PiGlowFunc	 func;
	gint		 interval;
	
	if (argc < 3 || argc > 4) {
		g_printerr ("usage: piglow <device> <effect> "
			    "[<interval in millisec>]\n");
		return 1;
	}

	func = get_effect_func (argv[2]);
	if (!func)
		return 1;

	interval = (argc == 4) ? atoi (argv[3]) : 200;
	if (interval <= 0) {
		g_printerr ("Invalid interval\n");
		return 1;
	}
		
	err = NULL;
	pig = pi_glow_new (argv[1], &err);
	if (!pig)
		goto errexit;

	if (!pi_glow_animate (pig, interval, func, NULL))
		goto errexit;
	
	loop = g_main_loop_new (NULL, TRUE);	
	g_unix_signal_add (SIGINT, (GSourceFunc)g_main_loop_quit, loop);
	g_print ("Press Ctrl-C to quit\n");
	g_main_loop_run (loop);
	
	g_clear_object (&pig);
	g_main_loop_unref (loop);
	
	return 0;
errexit:
	g_printerr ("Error: %s\n", err ? err->message :
		    "something went wrong\n");
	g_clear_error (&err);
	g_clear_object (&pig);

	return 1;
}
Example #19
0
/*
 * _gjs_profiler_setup_signals:
 * @context: a #GjsContext with a profiler attached
 *
 * If you want to simply allow profiling of your process with minimal
 * fuss, simply call gjs_profiler_setup_signals(). This will allow
 * enabling and disabling the profiler with SIGUSR2. You must call
 * this from main() immediately when your program starts and must not
 * block SIGUSR2 from your signal mask.
 *
 * If this is not sufficient, use gjs_profiler_chain_signal() from your
 * own signal handler to pass the signal to a GjsProfiler.
 */
void
_gjs_profiler_setup_signals(GjsProfiler *self,
                            GjsContext  *context)
{
    g_return_if_fail(context == profiling_context);

#ifdef ENABLE_PROFILER

    if (self->sigusr2_id != 0)
        return;

    self->sigusr2_id = g_unix_signal_add(SIGUSR2, gjs_profiler_sigusr2, context);

#else  /* !ENABLE_PROFILER */

    g_message("Profiler is disabled. Not setting up signals.");

#endif  /* ENABLE_PROFILER */
}
Example #20
0
/* function implementation */
zathura_t*
zathura_create(void)
{
  zathura_t* zathura = g_try_malloc0(sizeof(zathura_t));
  if (zathura == NULL) {
    return NULL;
  }

  /* global settings */
  zathura->global.search_direction = FORWARD;

  /* plugins */
  zathura->plugins.manager = zathura_plugin_manager_new();
  if (zathura->plugins.manager == NULL) {
    goto error_out;
  }

  /* UI */
  zathura->ui.session = girara_session_create();
  if (zathura->ui.session == NULL) {
    goto error_out;
  }

#ifdef G_OS_UNIX
  /* signal handler */
  zathura->signals.sigterm = g_unix_signal_add(SIGTERM, zathura_signal_sigterm, zathura);
#endif

  /* MIME type detection */
  zathura->content_type_context = zathura_content_type_new();

  zathura->ui.session->global.data = zathura;

  return zathura;

error_out:

  zathura_free(zathura);

  return NULL;
}
Example #21
0
int
main (int argc, char *argv[])
{
  SnraManager *manager;
  char *config_file = NULL;

  gst_init (&argc, &argv);

  if (argc > 1) 
    config_file = argv[1];

  g_unix_signal_add (SIGINT, sigint_handler, NULL);

  manager = snra_manager_new(config_file);
  if (manager == NULL)
    return -1;

  ml = g_main_loop_new(NULL, FALSE);
  g_main_loop_run(ml);

  g_object_unref (manager);
  return 0;
}
Example #22
0
static int
run_bridge (const gchar *interactive)
{
  CockpitTransport *transport;
  CockpitBridge *bridge;
  gboolean terminated = FALSE;
  gboolean interupted = FALSE;
  gboolean closed = FALSE;
  gboolean init_received = FALSE;
  guint sig_term;
  guint sig_int;
  int outfd;

  cockpit_set_journal_logging (G_LOG_DOMAIN, !isatty (2));

  /*
   * This process talks on stdin/stdout. However lots of stuff wants to write
   * to stdout, such as g_debug, and uses fd 1 to do that. Reroute fd 1 so that
   * it goes to stderr, and use another fd for stdout.
   */

  outfd = dup (1);
  if (outfd < 0 || dup2 (2, 1) < 1)
    {
      g_warning ("bridge couldn't redirect stdout to stderr");
      outfd = 1;
    }

  sig_term = g_unix_signal_add (SIGTERM, on_signal_done, &terminated);
  sig_int = g_unix_signal_add (SIGINT, on_signal_done, &interupted);

  g_type_init ();

  cockpit_dbus_json_allow_external = FALSE;

  packages = cockpit_packages_new ();
  cockpit_dbus_internal_startup (interactive != NULL);

  if (interactive)
    {
      /* Allow skipping the init message when interactive */
      init_received = TRUE;
      transport = cockpit_interact_transport_new (0, outfd, interactive);
    }
  else
    {
      transport = cockpit_pipe_transport_new_fds ("stdio", 0, outfd);
    }

  g_resources_register (cockpitassets_get_resource ());
  cockpit_web_failure_resource = "/org/cockpit-project/Cockpit/fail.html";

  bridge = cockpit_bridge_new (transport, payload_types, init_received);
  cockpit_dbus_environment_startup ();

  g_signal_connect (transport, "closed", G_CALLBACK (on_closed_set_flag), &closed);
  send_init_command (transport);

  while (!terminated && !closed && !interupted)
    g_main_context_iteration (NULL, TRUE);

  g_object_unref (bridge);
  g_object_unref (transport);
  cockpit_packages_free (packages);
  packages = NULL;

  g_source_remove (sig_term);
  g_source_remove (sig_int);

  /* So the caller gets the right signal */
  if (terminated)
    raise (SIGTERM);

  return 0;
}
Example #23
0
int main(int argc, char *argv[])
{
	GMainLoop *main_loop = NULL;
	GObject *scgi_server = NULL;
	static gchar *conf_dir = NULL;
	static gboolean debug = FALSE;
#ifdef G_OS_UNIX
	static gchar *user = NULL;
	static gchar *group = NULL;
#endif /* G_OS_UNIX */
	static GOptionEntry option_entries[] =
	{
		{ "conf", 'c', 0, G_OPTION_ARG_STRING,  &conf_dir, "Config directory", NULL},
#ifdef G_OS_UNIX
		{ "user", 'u', 0, G_OPTION_ARG_STRING,  &user, "User name", NULL},
		{ "group", 'g', 0, G_OPTION_ARG_STRING,  &group, "Group name", NULL},
#endif /* G_OS_UNIX */
		{ "debug", 'd', 0, G_OPTION_ARG_NONE,  &debug, "Debug mode", NULL},
		{ NULL }
	};
	GOptionContext *option_context = NULL;
	GError *error = NULL;

#ifndef GLIB_VERSION_2_36
	g_type_init();
#endif

	if(!g_module_supported())
	  g_error("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	option_context = g_option_context_new("");
	g_option_context_add_main_entries(option_context,
				option_entries, NULL);
	if(!g_option_context_parse(option_context, &argc, &argv, &error))
	{
		g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__, __FUNCTION__,
					error->message);
		g_error_free(error);
	}
	g_option_context_free(option_context);

#ifdef G_OS_UNIX
	if(group)
	{
		struct group *grp = NULL;

		if(NULL == (grp = getgrnam(group)))
		  g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
					  __FUNCTION__, "Get group failed!");

		if(-1 == setgid(grp->gr_gid))
		  g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
					  __FUNCTION__, "Set gid failed!");
		if(-1 == setgroups(0, NULL))
		  g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
					  __FUNCTION__, "Set groups failed!");
		if(user)
		{
			if(-1 == initgroups(user, grp->gr_gid))
			  g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
						  __FUNCTION__, "Init groups failed!");
		}
	}

	if(user)
	{
		struct passwd *pwd = NULL;

		if(NULL == (pwd = getpwnam(user)))
		  g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
					  __FUNCTION__, "Get user failed!");

		if(-1 == setuid(pwd->pw_uid))
		  g_error("%s:%d[%s]=>(%s)", __FILE__, __LINE__,
					  __FUNCTION__, "Set uid failed!");
	}
#endif /* G_OS_UNIX */

	if(!debug)
	{
		g_log_set_handler(NULL, G_LOG_LEVEL_DEBUG,
					debug_log_handler, NULL);
#ifdef G_OS_UNIX
		daemon(1, 1);
#endif /* G_OS_UNIX */
	}

	main_loop = g_main_loop_new(NULL, FALSE);
	if(!main_loop)
	  g_error("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	scgi_server = hev_scgi_server_new(conf_dir);
	if(!scgi_server)
	  g_error("%s:%d[%s]", __FILE__, __LINE__, __FUNCTION__);

	hev_scgi_server_start(HEV_SCGI_SERVER(scgi_server));
#ifdef G_OS_UNIX
	g_unix_signal_add(SIGINT, unix_signal_handler, main_loop);
	g_unix_signal_add(SIGTERM, unix_signal_handler, main_loop);
#endif /* G_OS_UNIX */

	g_main_loop_run(main_loop);

	hev_scgi_server_stop(HEV_SCGI_SERVER(scgi_server));

	g_object_unref(G_OBJECT(scgi_server));
	g_main_loop_unref(main_loop);

	return 0;
}
Example #24
0
int main ( int argc, char *argv[] )
{
    TIMINGS_START ();

    cmd_set_arguments ( argc, argv );

    // Version
    if ( find_arg (  "-v" ) >= 0 || find_arg (  "-version" ) >= 0 ) {
#ifdef GIT_VERSION
        fprintf ( stdout, "Version: "GIT_VERSION "\n" );
#else
        fprintf ( stdout, "Version: "VERSION "\n" );
#endif
        exit ( EXIT_SUCCESS );
    }

    // Detect if we are in dmenu mode.
    // This has two possible causes.
    // 1 the user specifies it on the command-line.
    if ( find_arg (  "-dmenu" ) >= 0 ) {
        dmenu_mode = TRUE;
    }
    // 2 the binary that executed is called dmenu (e.g. symlink to rofi)
    else{
        // Get the base name of the executable called.
        char *base_name = g_path_get_basename ( argv[0] );
        const char * const dmenu_str = "dmenu";
        dmenu_mode = ( strcmp ( base_name, dmenu_str ) == 0 );
        // Free the basename for dmenu detection.
        g_free ( base_name );
    }
    TICK ();
    // Get the path to the cache dir.
    cache_dir = g_get_user_cache_dir ();

    // Create pid file path.
    const char *path = g_get_user_runtime_dir ();
    if ( path ) {
        pidfile = g_build_filename ( path, "rofi.pid", NULL );
    }
    config_parser_add_option ( xrm_String, "pid", (void * *) &pidfile, "Pidfile location" );

    if ( find_arg ( "-config" ) < 0 ) {
        const char *cpath = g_get_user_config_dir ();
        if ( cpath ) {
            config_path = g_build_filename ( cpath, "rofi", "config", NULL );
        }
    }
    else {
        char *c = NULL;
        find_arg_str ( "-config", &c );
        config_path = rofi_expand_path ( c );
    }

    TICK ();
    // Register cleanup function.
    atexit ( cleanup );

    TICK ();
    // Get DISPLAY, first env, then argument.
    char *display_str = getenv ( "DISPLAY" );
    find_arg_str (  "-display", &display_str );

    if ( setlocale ( LC_ALL, "" ) == NULL ) {
        fprintf ( stderr, "Failed to set locale.\n" );
        return EXIT_FAILURE;
    }

    xcb->connection = xcb_connect ( display_str, &xcb->screen_nbr );
    if ( xcb_connection_has_error ( xcb->connection ) ) {
        fprintf ( stderr, "Failed to open display: %s", display_str );
        return EXIT_FAILURE;
    }
    TICK_N ( "Open Display" );

    xcb->screen = xcb_aux_get_screen ( xcb->connection, xcb->screen_nbr );

    xcb_intern_atom_cookie_t *ac     = xcb_ewmh_init_atoms ( xcb->connection, &xcb->ewmh );
    xcb_generic_error_t      *errors = NULL;
    xcb_ewmh_init_atoms_replies ( &xcb->ewmh, ac, &errors );
    if ( errors ) {
        fprintf ( stderr, "Failed to create EWMH atoms\n" );
        free ( errors );
    }

    if ( xkb_x11_setup_xkb_extension ( xcb->connection, XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION,
                                       XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS, NULL, NULL, &xkb.first_event, NULL ) < 0 ) {
        fprintf ( stderr, "cannot setup XKB extension!\n" );
        return EXIT_FAILURE;
    }

    xkb.context = xkb_context_new ( XKB_CONTEXT_NO_FLAGS );
    if ( xkb.context == NULL ) {
        fprintf ( stderr, "cannot create XKB context!\n" );
        return EXIT_FAILURE;
    }
    xkb.xcb_connection = xcb->connection;

    xkb.device_id = xkb_x11_get_core_keyboard_device_id ( xcb->connection );

    enum
    {
        required_events =
            ( XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
              XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
              XCB_XKB_EVENT_TYPE_STATE_NOTIFY ),

        required_nkn_details =
            ( XCB_XKB_NKN_DETAIL_KEYCODES ),

        required_map_parts   =
            ( XCB_XKB_MAP_PART_KEY_TYPES |
              XCB_XKB_MAP_PART_KEY_SYMS |
              XCB_XKB_MAP_PART_MODIFIER_MAP |
              XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
              XCB_XKB_MAP_PART_KEY_ACTIONS |
              XCB_XKB_MAP_PART_VIRTUAL_MODS |
              XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP ),

        required_state_details =
            ( XCB_XKB_STATE_PART_MODIFIER_BASE |
              XCB_XKB_STATE_PART_MODIFIER_LATCH |
              XCB_XKB_STATE_PART_MODIFIER_LOCK |
              XCB_XKB_STATE_PART_GROUP_BASE |
              XCB_XKB_STATE_PART_GROUP_LATCH |
              XCB_XKB_STATE_PART_GROUP_LOCK ),
    };

    static const xcb_xkb_select_events_details_t details = {
        .affectNewKeyboard  = required_nkn_details,
        .newKeyboardDetails = required_nkn_details,
        .affectState        = required_state_details,
        .stateDetails       = required_state_details,
    };
    xcb_xkb_select_events ( xcb->connection, xkb.device_id, required_events, /* affectWhich */
                            0,                                               /* clear */
                            required_events,                                 /* selectAll */
                            required_map_parts,                              /* affectMap */
                            required_map_parts,                              /* map */
                            &details );

    xkb.keymap = xkb_x11_keymap_new_from_device ( xkb.context, xcb->connection, xkb.device_id, XKB_KEYMAP_COMPILE_NO_FLAGS );
    if ( xkb.keymap == NULL ) {
        fprintf ( stderr, "Failed to get Keymap for current keyboard device.\n" );
        return EXIT_FAILURE;
    }
    xkb.state = xkb_x11_state_new_from_device ( xkb.keymap, xcb->connection, xkb.device_id );
    if ( xkb.state == NULL ) {
        fprintf ( stderr, "Failed to get state object for current keyboard device.\n" );
        return EXIT_FAILURE;
    }

    xkb.compose.table = xkb_compose_table_new_from_locale ( xkb.context, setlocale ( LC_CTYPE, NULL ), 0 );
    if ( xkb.compose.table != NULL ) {
        xkb.compose.state = xkb_compose_state_new ( xkb.compose.table, 0 );
    }
    else {
        fprintf ( stderr, "Failed to get keyboard compose table. Trying to limp on.\n" );
    }

    if ( xcb_connection_has_error ( xcb->connection ) ) {
        fprintf ( stderr, "Connection has error\n" );
        exit ( EXIT_FAILURE );
    }
    x11_setup ( &xkb );
    if ( xcb_connection_has_error ( xcb->connection ) ) {
        fprintf ( stderr, "Connection has error\n" );
        exit ( EXIT_FAILURE );
    }

    const xcb_query_extension_reply_t *er = xcb_get_extension_data ( xcb->connection, &xcb_xinerama_id );
    if ( er ) {
        if ( er->present ) {
            xcb_xinerama_is_active_cookie_t is_active_req = xcb_xinerama_is_active ( xcb->connection );
            xcb_xinerama_is_active_reply_t  *is_active    = xcb_xinerama_is_active_reply ( xcb->connection, is_active_req, NULL );
            xcb->has_xinerama = is_active->state;
            free ( is_active );
        }
    }
    main_loop = g_main_loop_new ( NULL, FALSE );

    TICK_N ( "Setup mainloop" );
    // startup not.
    xcb->sndisplay = sn_xcb_display_new ( xcb->connection, error_trap_push, error_trap_pop );
    if ( xcb_connection_has_error ( xcb->connection ) ) {
        fprintf ( stderr, "Connection has error\n" );
        exit ( EXIT_FAILURE );
    }

    if ( xcb->sndisplay != NULL ) {
        xcb->sncontext = sn_launchee_context_new_from_environment ( xcb->sndisplay, xcb->screen_nbr );
    }
    if ( xcb_connection_has_error ( xcb->connection ) ) {
        fprintf ( stderr, "Connection has error\n" );
        exit ( EXIT_FAILURE );
    }
    TICK_N ( "Startup Notification" );

    // Initialize Xresources subsystem.
    config_parse_xresource_init ();
    TICK_N ( "Initialize Xresources system" );
    // Setup keybinding
    setup_abe ();
    TICK_N ( "Setup abe" );

    if ( find_arg ( "-no-config" ) < 0 ) {
        load_configuration ( );
    }
    if ( !dmenu_mode ) {
        // setup_modi
        setup_modi ();
    }

    if ( find_arg ( "-no-config" ) < 0 ) {
        // Reload for dynamic part.
        load_configuration_dynamic ( );
    }
    // Dump.
    // catch help request
    if ( find_arg (  "-h" ) >= 0 || find_arg (  "-help" ) >= 0 || find_arg (  "--help" ) >= 0 ) {
        help ( argc, argv );
        exit ( EXIT_SUCCESS );
    }
    if ( find_arg (  "-dump-xresources" ) >= 0 ) {
        config_parse_xresource_dump ();
        exit ( EXIT_SUCCESS );
    }
    if ( find_arg (  "-dump-xresources-theme" ) >= 0 ) {
        config_parse_xresources_theme_dump ();
        exit ( EXIT_SUCCESS );
    }

    main_loop_source = g_water_xcb_source_new_for_connection ( NULL, xcb->connection, main_loop_x11_event_handler, NULL, NULL );

    TICK_N ( "X11 Setup " );

    rofi_view_workers_initialize ();

    // Setup signal handling sources.
    // SIGINT
    g_unix_signal_add ( SIGINT, main_loop_signal_handler_int, NULL );

    g_idle_add ( startup, NULL );

    // Start mainloop.
    g_main_loop_run ( main_loop );

    return return_code;
}
Example #25
0
int
main (int argc,
      char **argv)
{
  CockpitTransport *transport;
  gboolean terminated = FALSE;
  gboolean interupted = FALSE;
  gboolean closed = FALSE;
  GOptionContext *context;
  GError *error = NULL;
  guint sig_term;
  guint sig_int;
  int outfd;

  static GOptionEntry entries[] = {
    { "lower", 0, 0, G_OPTION_ARG_NONE, &opt_lower, "Lower case channel type", NULL },
    { "upper", 0, 0, G_OPTION_ARG_NONE, &opt_upper, "Upper case channel type", NULL },
    { NULL }
  };

  signal (SIGPIPE, SIG_IGN);

  g_setenv ("GSETTINGS_BACKEND", "memory", TRUE);
  g_setenv ("GIO_USE_PROXY_RESOLVER", "dummy", TRUE);
  g_setenv ("GIO_USE_VFS", "local", TRUE);

  context = g_option_context_new (NULL);
  g_option_context_add_main_entries (context, entries, NULL);
  g_option_context_set_description (context, "mock-bridge as used in tests\n");

  g_option_context_parse (context, &argc, &argv, &error);
  g_option_context_free (context);

  if (error)
    {
      g_printerr ("mock-bridge: %s\n", error->message);
      g_error_free (error);
      return 1;
    }

  outfd = dup (1);
  if (outfd < 0 || dup2 (2, 1) < 1)
    {
      g_warning ("bridge couldn't redirect stdout to stderr");
      outfd = 1;
    }

  sig_term = g_unix_signal_add (SIGTERM, on_signal_done, &terminated);
  sig_int = g_unix_signal_add (SIGINT, on_signal_done, &interupted);

  g_type_init ();

  transport = cockpit_pipe_transport_new_fds ("stdio", 0, outfd);

  g_signal_connect (transport, "control", G_CALLBACK (on_transport_control), NULL);
  g_signal_connect (transport, "closed", G_CALLBACK (on_closed_set_flag), &closed);
  send_init_command (transport);

  /* Owns the channels */
  channels = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);

  while (!terminated && !closed && !interupted)
    g_main_context_iteration (NULL, TRUE);

  g_object_unref (transport);
  g_hash_table_destroy (channels);

  g_source_remove (sig_term);
  g_source_remove (sig_int);

  /* So the caller gets the right signal */
  if (terminated)
    raise (SIGTERM);

  return 0;
}
Example #26
0
int main(int argc, char *argv[])
{

    history = g_queue_new();
    displayed = g_queue_new();
    queue = g_queue_new();

    cmdline_load(argc, argv);

    if (cmdline_get_bool("-v/-version", false, "Print version")
            || cmdline_get_bool("--version", false, "Print version")) {
        print_version();
    }

    char *cmdline_config_path;
    cmdline_config_path =
        cmdline_get_string("-conf/-config", NULL,
                           "Path to configuration file");
    load_settings(cmdline_config_path);

    if (cmdline_get_bool("-h/-help", false, "Print help")
            || cmdline_get_bool("--help", false, "Print help")) {
        usage(EXIT_SUCCESS);
    }

    int owner_id = initdbus();

    x_setup();

    if (settings.startup_notification) {
        notification *n = malloc(sizeof(notification));
        if(n == NULL) {
            die("Unable to allocate memory", EXIT_FAILURE);
        }
        n->appname = strdup("dunst");
        n->summary = strdup("startup");
        n->body = strdup("dunst is up and running");
        n->progress = 0;
        n->timeout = 10;
        n->allow_markup = false;
        n->plain_text = true;
        n->urgency = LOW;
        n->icon = NULL;
        n->raw_icon = NULL;
        n->category = NULL;
        n->msg = NULL;
        n->dbus_client = NULL;
        n->color_strings[0] = NULL;
        n->color_strings[1] = NULL;
        n->actions = NULL;
        n->urls = NULL;
        notification_init(n, 0);
    }

    mainloop = g_main_loop_new(NULL, FALSE);

    GPollFD dpy_pollfd = { xctx.dpy->fd,
                           G_IO_IN | G_IO_HUP | G_IO_ERR, 0
                         };

    GSourceFuncs x11_source_funcs = {
        x_mainloop_fd_prepare,
        x_mainloop_fd_check,
        x_mainloop_fd_dispatch,
        NULL,
        NULL,
        NULL
    };

    GSource *x11_source =
        g_source_new(&x11_source_funcs, sizeof(x11_source_t));
    ((x11_source_t *) x11_source)->dpy = xctx.dpy;
    ((x11_source_t *) x11_source)->w = xctx.win;
    g_source_add_poll(x11_source, &dpy_pollfd);

    g_source_attach(x11_source, NULL);

    g_unix_signal_add(SIGUSR1, pause_signal, NULL);
    g_unix_signal_add(SIGUSR2, unpause_signal, NULL);

    run(NULL);
    g_main_loop_run(mainloop);

    dbus_tear_down(owner_id);

    return 0;
}
Example #27
0
int      S52_utils_initSIG(void)
// init signal handler
{

#ifdef S52_USE_MINGW
    signal(SIGINT,  _trapSIG);  //  2 - Interrupt (ANSI).
    signal(SIGSEGV, _trapSIG);  // 11 - Segmentation violation (ANSI).

#else  // S52_USE_MINGW

    //struct sigaction sa;

    //memset(&sa, 0, sizeof(sa));
    //sa.sa_sigaction = _trapSIG;
    //sigemptyset(&sa.sa_mask);
    //sa.sa_flags = SA_SIGINFO;  // -std=c99 -D_POSIX_C_SOURCE=199309L

    guint eventID = 0;

    // 1 - SIGHUP: (POSIX) controlling terminal is closed.
    eventID = g_unix_signal_add(SIGHUP, _trapSIG, GINT_TO_POINTER(SIGHUP));
    if (0 >= eventID) {
        PRINTF("WARNING: GLib Signal add SIG(%i) failed\n", SIGHUP);
    }

    //  2 - SIGINT: Interrupt (ANSI) - Ctrl-C
    // abort long running process in _draw(), _drawLast() and _suppLineOverlap()
    g_atomic_int_set(&_atomicAbort, FALSE);

    //sigaction(SIGINT,  &sa, &_old_signal_handler_SIGINT);
    eventID = g_unix_signal_add(SIGINT, _trapSIG, GINT_TO_POINTER(SIGINT));
    if (0 >= eventID) {
        PRINTF("WARNING: GLib Signal add SIG(%i) failed\n", SIGINT);
    }

    //  3 - Quit (POSIX)
    //sigaction(SIGQUIT, &sa, &_old_signal_handler_SIGQUIT);
    //  5 - Trap (ANSI)
    //sigaction(SIGTRAP, &sa, &_old_signal_handler_SIGTRAP);
    //  6 - Abort (ANSI)
    //sigaction(SIGABRT, &sa, &_old_signal_handler_SIGABRT);
    //  9 - Kill, unblock-able (POSIX)
    //sigaction(SIGKILL, &sa, &_old_signal_handler_SIGKILL);
    // 11 - Segmentation violation (ANSI).
    //sigaction(SIGSEGV, &sa, &_old_signal_handler_SIGSEGV);   // loop in android

    // 15 - SIGTERM: Termination (ANSI)
    //sigaction(SIGTERM, &sa, &_old_signal_handler_SIGTERM);
    eventID = g_unix_signal_add(SIGTERM, _trapSIG, GINT_TO_POINTER(SIGTERM));
    if (0 >= eventID) {
        PRINTF("WARNING: GLib Signal add SIG(%i) failed\n", SIGTERM);
    }

    // 10 - SIGUSR1
    //sigaction(SIGUSR1, &sa, &_old_signal_handler_SIGUSR1);
    eventID = g_unix_signal_add(SIGUSR1, _trapSIG, GINT_TO_POINTER(SIGUSR1));
    if (0 >= eventID) {
        PRINTF("WARNING: GLib Signal add SIG(%i) failed\n", SIGUSR1);
    }

    // 12 - SIGUSR2
    //sigaction(SIGUSR2, &sa, &_old_signal_handler_SIGUSR2);
    eventID = g_unix_signal_add(SIGUSR2, _trapSIG, GINT_TO_POINTER(SIGUSR2));
    if (0 >= eventID) {
        PRINTF("WARNING: GLib Signal add SIG(%i) failed\n", SIGUSR2);
    }

    // 28 - SIGWINCH: window full-screen - glib 2.54
    //eventID = g_unix_signal_add(SIGWINCH, _trapSIG, GINT_TO_POINTER(SIGWINCH));
    //if (0 >= eventID) {
    //    PRINTF("WARNING: GLib Signal add SIG(%i) failed\n", SIGWINCH);
    //}


#endif  // S52_USE_MINGW

    return TRUE;
}
Example #28
0
int
main (int argc, char **argv)
{
    int i;
    char *pid_string;
    gchar *seat = NULL;
    gchar *mir_id = NULL;
    gchar *lock_filename;
    gboolean sharevts = FALSE;
    int lock_file;
    GString *status_text;

#if !defined(GLIB_VERSION_2_36)
    g_type_init ();
#endif

    loop = g_main_loop_new (NULL, FALSE);

    g_unix_signal_add (SIGINT, sigint_cb, NULL);
    g_unix_signal_add (SIGTERM, sigterm_cb, NULL);
    g_unix_signal_add (SIGHUP, sighup_cb, NULL);

    for (i = 1; i < argc; i++)
    {
        char *arg = argv[i];

        if (arg[0] == ':')
        {
            display_number = atoi (arg + 1);
        }
        else if (strcmp (arg, "-auth") == 0)
        {
            auth_path = argv[i+1];
            i++;
        }
        else if (strcmp (arg, "-nolisten") == 0)
        {
            char *protocol = argv[i+1];
            i++;
            if (strcmp (protocol, "tcp") == 0)
                ;//listen_tcp = FALSE;
            else if (strcmp (protocol, "unix") == 0)
                ;//listen_unix = FALSE;
        }
        else if (strcmp (arg, "-nr") == 0)
        {
        }
        else if (strcmp (arg, "-background") == 0)
        {
            /* Ignore arg */
            i++;
        }
        else if (g_str_has_prefix (arg, "vt"))
        {
            vt_number = atoi (arg + 2);
        }
        else if (strcmp (arg, "-novtswitch") == 0)
        {
            /* Ignore VT args */
        }
        else if (strcmp (arg, "-seat") == 0)
        {
            seat = argv[i+1];
            i++;
        }
        else if (strcmp (arg, "-sharevts") == 0)
        {
            sharevts = TRUE;
        }
        else if (strcmp (arg, "-mir") == 0)
        {
            mir_id = argv[i+1];
            i++;
        }
        else if (strcmp (arg, "-mirSocket") == 0)
        {
            /* FIXME */
            i++;
        }
        else
        {
            g_printerr ("Unrecognized option: %s\n"
                        "Use: %s [:<display>] [option]\n"
                        "-auth file             Select authorization file\n"
                        "-nolisten protocol     Don't listen on protocol\n"
                        "-background [none]     Create root window with no background\n"
                        "-nr                    (Ubuntu-specific) Synonym for -background none\n"
                        "-seat string           seat to run on\n"
                        "-sharevts              share VTs with another X server\n"
                        "-mir id                Mir ID to use\n"
                        "-mirSocket name        Mir socket to use\n"
                        "vtxx                   Use virtual terminal xx instead of the next available\n",
                        arg, argv[0]);
            return EXIT_FAILURE;
        }
    }

    id = g_strdup_printf ("XMIR-%d", display_number);

    status_connect (request_cb, id);

    xserver = x_server_new (display_number);
    g_signal_connect (xserver, X_SERVER_SIGNAL_CLIENT_CONNECTED, G_CALLBACK (client_connected_cb), NULL);
    g_signal_connect (xserver, X_SERVER_SIGNAL_CLIENT_DISCONNECTED, G_CALLBACK (client_disconnected_cb), NULL);

    status_text = g_string_new ("");
    g_string_printf (status_text, "%s START", id);
    if (vt_number >= 0)
        g_string_append_printf (status_text, " VT=%d", vt_number);
    if (seat != NULL)
        g_string_append_printf (status_text, " SEAT=%s", seat);
    if (sharevts)
        g_string_append (status_text, " SHAREVTS=TRUE");
    if (mir_id != NULL)
        g_string_append_printf (status_text, " MIR-ID=%s", mir_id);
    status_notify ("%s", status_text->str);
    g_string_free (status_text, TRUE);

    config = g_key_file_new ();
    g_key_file_load_from_file (config, g_build_filename (g_getenv ("LIGHTDM_TEST_ROOT"), "script", NULL), G_KEY_FILE_NONE, NULL);

    if (g_key_file_has_key (config, "test-xserver-config", "return-value", NULL))
    {
        int return_value = g_key_file_get_integer (config, "test-xserver-config", "return-value", NULL);
        status_notify ("%s EXIT CODE=%d", id, return_value);
        return return_value;
    }

    lock_filename = g_strdup_printf (".X%d-lock", display_number);
    lock_path = g_build_filename (g_getenv ("LIGHTDM_TEST_ROOT"), "tmp", lock_filename, NULL);
    g_free (lock_filename);
    lock_file = open (lock_path, O_CREAT | O_EXCL | O_WRONLY, 0444);
    if (lock_file < 0)
    {
        char *lock_contents = NULL;

        if (g_file_get_contents (lock_path, &lock_contents, NULL, NULL))
        {
            gchar *proc_filename;
            pid_t pid;

            pid = atol (lock_contents);
            g_free (lock_contents);

            proc_filename = g_strdup_printf ("/proc/%d", pid);
            if (!g_file_test (proc_filename, G_FILE_TEST_EXISTS))
            {
                gchar *socket_dir;
                gchar *socket_filename;
                gchar *socket_path;

                socket_dir = g_build_filename (g_getenv ("LIGHTDM_TEST_ROOT"), "tmp", ".X11-unix", NULL);
                g_mkdir_with_parents (socket_dir, 0755);

                socket_filename = g_strdup_printf ("X%d", display_number);
                socket_path = g_build_filename (socket_dir, socket_filename, NULL);

                g_printerr ("Breaking lock on non-existant process %d\n", pid);
                unlink (lock_path);
                unlink (socket_path);

                g_free (socket_dir);
                g_free (socket_filename);
                g_free (socket_path);
            }
            g_free (proc_filename);

            lock_file = open (lock_path, O_CREAT | O_EXCL | O_WRONLY, 0444);
        }
    }
    if (lock_file < 0)
    {
        fprintf (stderr,
                 "Fatal server error:\n"
                 "Server is already active for display %d\n"
                 "	If this server is no longer running, remove %s\n"
                 "	and start again.\n", display_number, lock_path);
        g_free (lock_path);
        lock_path = NULL;
        return EXIT_FAILURE;
    }
    pid_string = g_strdup_printf ("%10ld", (long) getpid ());
    if (write (lock_file, pid_string, strlen (pid_string)) < 0)
    {
        g_warning ("Error writing PID file: %s", strerror (errno));
        return EXIT_FAILURE;
    }
    g_free (pid_string);

    if (!x_server_start (xserver))
        return EXIT_FAILURE;

    g_main_loop_run (loop);

    cleanup ();

    return exit_status;
}
Example #29
0
int
main (int argc, char **argv)
{
    g_debug (G_STRLOC ": %s", G_STRFUNC);

    DasomServer *server;
    GMainLoop   *loop;
    GError      *error = NULL;

    gboolean is_no_daemon = FALSE;
    gboolean is_debug     = FALSE;
    gboolean is_version   = FALSE;

    GOptionContext *context;
    GOptionEntry    entries[] = {
        {"no-daemon", 0, 0, G_OPTION_ARG_NONE, &is_no_daemon, N_("Do not daemonize"), NULL},
        {"debug", 0, 0, G_OPTION_ARG_NONE, &is_debug, N_("Log debugging message"), NULL},
        {"version", 0, 0, G_OPTION_ARG_NONE, &is_version, N_("Version"), NULL},
        {NULL}
    };

    context = g_option_context_new ("- Dasom Input Method Daemon");
    g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
    g_option_context_parse (context, &argc, &argv, &error);
    g_option_context_free (context);

    if (error != NULL)
    {
        g_warning ("%s", error->message);
        g_error_free (error);
        return EXIT_FAILURE;
    }

#if ENABLE_NLS
    bindtextdomain (GETTEXT_PACKAGE, DASOM_LOCALE_DIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);
#endif

    if (is_version)
    {
        g_print ("%s %s\n", argv[0], VERSION);
        exit (EXIT_SUCCESS);
    }

    if (is_no_daemon == FALSE)
    {
        openlog (g_get_prgname (), LOG_PID | LOG_PERROR, LOG_DAEMON);
        syslog_initialized = TRUE;
        g_log_set_default_handler ((GLogFunc) dasom_log_default_handler, &is_debug);

        if (daemon (0, 0) != 0)
        {
            g_critical ("Couldn't daemonize.");
            return EXIT_FAILURE;
        }
    }

    server = dasom_server_new ("unix:abstract=dasom", &error);

    if (server == NULL)
    {
        g_critical ("%s", error->message);
        g_clear_error (&error);

        return EXIT_FAILURE;
    }

    dasom_server_start (server);

    loop = g_main_loop_new (NULL, FALSE);

    g_unix_signal_add (SIGINT,  (GSourceFunc) g_main_loop_quit, loop);
    g_unix_signal_add (SIGTERM, (GSourceFunc) g_main_loop_quit, loop);

    g_main_loop_run (loop);

    g_main_loop_unref (loop);
    g_object_unref (server);

    if (syslog_initialized)
        closelog ();

    return EXIT_SUCCESS;
}
Example #30
-1
static void
initialize_signal_handler (GMainLoop *loop)
{
#ifndef G_OS_WIN32
    g_unix_signal_add (SIGTERM, signal_handler, loop);
    g_unix_signal_add (SIGINT, signal_handler, loop);
#endif /* G_OS_WIN32 */
}